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