在 mvc 中填充我的 m viewModel 模型

Fill my model of m viewModel in mvc

我尝试填充我的模型,它是视图模型的成员, 我将数据从 Action 发送到 view.It 的工作正确。但是当点击保存按钮时,出现

错误

Object reference not set to an instance of an object.

视图模型是

public class OrderCustomer
{
    public Order Order { get; set; }
    public ApplicationUser ApplicationUser { get; set; }
}

post 数据的操作是

        [HttpPost]
    public ActionResult AddressAndPayment(OrderCustomer values)
    {
        var orderCustomer = new OrderCustomer();
        var order = orderCustomer.Order;

        string uId = User.Identity.GetUserId();
        order.Username = User.Identity.Name;
        order.ApplicationUserId = uId;
        order.OrderDate = DateTime.Now;
        order.Address = values.ApplicationUser.Address;
        order.CityId = (int)values.ApplicationUser.CityId;
        order.CountryId = (int)values.ApplicationUser.CountryId;
        order.Email = values.ApplicationUser.Email;
        order.FirstName = values.ApplicationUser.FName;
        order.LastName = values.ApplicationUser.LName;
        order.Phone = values.ApplicationUser.Phone;
        order.PostalCode = values.ApplicationUser.PostalCode;
        order.ProvinceId = (int)values.ApplicationUser.ProvinceId;

        if (ModelState.IsValid)
        {

            TryUpdateModel(order);

            try
            {
                _db.Orders.Add(order);
                _db.SaveChanges();
                var cart = ShoppingCart.GetCart(this.HttpContext);
                cart.CreateOrder(order);

                return RedirectToAction("Index", "Payment", new { id = order.Id });

            }
            catch
            {
               return View(order);
            }
        }
        return View(order);


    }

当调试器到达此代码时显示上面代码中的错误行 5,如下所示,我该如何解决?

        order.Username = User.Identity.Name;

鉴于OrderCustomer在初始化的时候没有初始化Order

喜欢

public class OrderCustomer {

    public OrderCustomer () {
        Order = new Order();
    }

    public Order Order { get; set; }
    public ApplicationUser ApplicationUser { get; set; }
}

那么 Order 默认为 null

这意味着当前您创建了 OrderCustomer 的实例,但从未将值分配给 Order 属性。

 var orderCustomer = new OrderCustomer();
 var order = orderCustomer.Order; //<-- Order is null by default

因此 ordernull,因为您没有为该变量分配对象。

因此,要么重构为上面的示例,要么确保创建一个新实例。

var orderCustomer = new OrderCustomer() {
    Order = new Order()
};

var order = orderCustomer.Order;
//...code removed for brevity

然而,这现在引出了一个问题,为什么您不从作为视图模型的一部分发布的内容分配该值?

我相信这就是你想要的

var order = values.Order;