视图中发生异常

时间:2019-04-24 12:35:38

标签: c# asp.net-mvc entity-framework linq

我有例外

  

对象引用未设置为对象的实例

在ASP.NET MVC中,当我发布具有多个模型的表单数据时。

这是我的“ ViewModel”类:

    public class CustomerViewModel
    {
        public Customer Customer { get; set; }
        public IEnumerable<tblGender> Genders  { get; set; }
        public IEnumerable<tblCountry> Countries { get; set; }
    }

这是Edit操作方法:

[HttpGet]
public ActionResult Edit(int id) 
{
            var customer = _context.Customers
.FirstOrDefault(c => c.Id == id);
            var viewModel = new CustomerViewModel()
            {
                Customer = customer,
                Genders = _context.tblGenders.ToList(),
                Countries = _context.tblCountries.ToList()
            };
            return View("Edit",viewModel);
}

[HttpPost]
public ActionResult Edit(Customer customer)
{
            var cust = _context.Customers.Single(c => c.Id == customer.Id);
            TryUpdateModel(cust);
            _context.SaveChanges();
            return RedirectToAction("Index", "Customer");
}

Create.cshtml

此部分中发生错误

   <div class="form-group">
          @Html.LabelFor(m => m.Customer.Gender)
        @Html.DropDownListFor(m => m.Customer.Gender, new    SelectList(Model.Genders, "Id", "GenderName"), "Select Gender", new { @class = "form-control" })
    </div>

2 个答案:

答案 0 :(得分:2)

在这段代码中,您的变量客户可以为空:

var customer = _context.Customers.FirstOrDefault(c => c.Id == id);

在这段代码中,您正在为模型分配该变量。客户:

var viewModel = new CustomerViewModel()
            {
                Customer = customer,

在这段代码中,您正在使用model.Customer,就像您确定它不是null一样:

@Html.LabelFor(m => m.Customer.Gender)

在许多其他可能性中,这是我能找到的最明显的null引用。 要解决此问题,您可以执行以下操作:

var viewModel = new CustomerViewModel()
            {
                Customer = customer ?? new Customer(),

或者这个:

var customer = _context.Customers.FirstOrDefault(c => c.Id == id);
if (customer == null) {
  return view("CustomerNotFound"); //or some other way to display your error
}

答案 1 :(得分:0)

关于对象引用异常。您是否创建了正在使用的对象的实例? 例如:

private readonly CustomerViewModel _customerViewModel;
_customerViewModel = new CustomerViewModel();