【发布时间】:2017-08-31 18:27:53
【问题描述】:
我尝试填充作为视图模型成员的模型, 我将数据从 Action 发送到 view。它工作正常。但是当点击保存按钮时,得到一个错误,
对象引用未设置为对象的实例。
视图模型是
public class OrderCustomer
{
public Order Order { get; set; }
public ApplicationUser ApplicationUser { get; set; }
}
发布数据的操作是
[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;
【问题讨论】:
-
可能请求未通过身份验证,因此没有设置身份 - 查看您的身份验证代码或设置像这样的匿名主体 stackoverflow.com/questions/2893334/…
-
order是null。您没有为该属性分配实例
标签: c# asp.net-mvc asp.net-mvc-4 viewmodel