0
我使用视图模型来显示一个下拉列表,我也试图让所选择的列表中值的对象错误的实例,这里是我的视图模型Html.ListBoxFor对象引用未设置为
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");
}
}
每次我尝试提交选定的VA我得到对象引用未设置为对象的实例在我的视图中的以下行上的错误:
@model Taw.WebUI.Models.CreateJobViewModel
@Html.ListBoxFor(m => m.SelectedIndustriesIds, Model.IndustriesList) -- here i get the error
任何原因为什么?
当您第一次加载或仅当您发布时才会出现错误? – dotnetstep 2014-10-31 02:26:57
我怀疑这是因为你在POST方法和catch块中获得异常返回视图。当你返回视图时,你首先需要重新分配'IndustriesList'的值,否则它的'null'和视图中的异常被抛出。 – 2014-10-31 02:37:35
@Stephen yea我的帖子操作存在一些问题,但我不知道它是什么 – Mindless 2014-10-31 03:11:32