Html.ListBoxFor对象引用未设置为对象错误的实例

Html.ListBoxFor对象引用未设置为对象错误的实例,html,asp.net-mvc,entity-framework,listbox,Html,Asp.net Mvc,Entity Framework,Listbox,我使用视图模型来显示下拉列表,我还试图获取所选列表的值,这是我的视图模型 public class CreateJobViewModel { public int[] SelectedIndustriesIds { get; set; } public IList<SelectListItem> IndustriesList { get; set; } } 我的邮政管理员 public ActionResult Create() { var industry

我使用视图模型来显示下拉列表,我还试图获取所选列表的值,这是我的视图模型

public class CreateJobViewModel
{
    public int[] SelectedIndustriesIds { get; set; }
    public IList<SelectListItem> IndustriesList { get; set; }
}
我的邮政管理员

public ActionResult Create()
{
    var industryList = repository.GetAllIndustries();

    var model = new CreateJobViewModel
    {
        IndustriesList = industryList.Select(i => new SelectListItem
        {
            Value = i.IndustryId.ToString(),
            Text = i.Name
        }).ToList()
    };

    return View("~/Views/Dashboard/Job/Create.cshtml", model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CreateJobViewModel model)
{

    try
    {
        var job = new Job()
        {
            Title = "hi",
            EmploymentHourId = 1,
            LocationId = 1,
            Salary = 50,
            SalaryPeriodId = 1,
            PostCode = 2131,
            Role = "world",
            Description = "hello",
            IsPublished = false,
            ShiftId = 1,
            WorkDayId = 1,
            NumberOfPosition = 5,
            Meal = false,
            SecondYearVisa = true,
            Sponsorship = true,
            Accommodation = true,
            DurationId = 1,
            IndustryExperiencePeriod = 5,
            Id = User.Identity.GetUserId(),


        };
        foreach (int id in model.SelectedIndustriesIds)
        {
            var industry = repository.Industry(id);
            job.Industries.Add(industry);
        }



        foreach (int id in model.SelectedSpecialRequirementsId)
        {
            var special = repository.SpecialRequirement(id);
            job.SpecialRequirements.Add(special);
        }

        repository.AddJob(job);

        return RedirectToAction("Create");
    }
    catch
    {
        return View("~/Views/Dashboard/Job/Create.cshtml");
    }
}
每次尝试提交所选值时,我都会在视图中的下一行将对象引用未设置为对象错误的实例:

@model Taw.WebUI.Models.CreateJobViewModel

@Html.ListBoxFor(m => m.SelectedIndustriesIds, Model.IndustriesList) -- here i get the error

任何原因?

当您提交表单时抛出异常(在注释中确认),并且在
catch
块中返回视图,该视图抛出您看到的异常,因为
Model.IndustriesList
为空。在返回视图之前,需要重新指定该值

由于如果返回视图,需要在GET方法和POST方法中分配
SelectList
s,因此我倾向于将其重新分配到单独的方法,以保持控制器代码更干净。注意:下面的代码基于您的模型属性
public SelectList IndustriesList{get;set;}
,这比构建
IList

然后在动作方法上

public ActionResult Create()
{
  var model = new CreateJobViewModel();
  ConfigureViewModel(model);
  return View(model);
}

public ActionResult Create(CreateJobViewModel model)
{
  try
  {
    ....
  }
  catch
  {
    ConfigureViewModel(model);
    return View(model);
  }
}
请注意,在尝试保存模型之前测试模型是否有效也是一种很好的做法

public ActionResult Create(CreateJobViewModel model)
{
  if (!ModelState.IsValid)
  {
    ConfigureViewModel(model);
    return View(model); // return the view so the user can correct validation errors
  }
  ....

您是在首次加载时出错,还是仅在发布时出错?我怀疑这是因为您在post方法和catch块中获得异常,从而返回视图。返回视图时,首先需要重新指定
IndustriesList
的值,否则它的
null
将引发视图上的异常。@Stephen yea我的post操作有一些问题,但我不知道它是什么添加断点并逐步执行它。但要解决眼前的问题,只需在返回之前再次分配
行业列表的值。作为旁注
public SelectList IndustriesList{get;set;}
model.IndustriesList=new SelectList(industryList,“IndustryId”,“Name”)太多了easier@Stephen谢谢,我解决了这个问题,在我的绑定中,我创建了一个新的自定义模型绑定器,但是您知道如何在自定义模型绑定器中获取所有选定的IndustriesID值吗?我尝试了var industries=bindingContext.ValueProvider.GetValue(“SelectedIndustriesIds”).AttemptedValue.ToArray(),但这不起作用
public ActionResult Create(CreateJobViewModel model)
{
  if (!ModelState.IsValid)
  {
    ConfigureViewModel(model);
    return View(model); // return the view so the user can correct validation errors
  }
  ....