嗨,我有一张工作表,上面有特定的工作ID
id title
1 Manager
2 Engineer
3 IT
我创建了一种方法,以便能够使用此表和数据从数据库中加载这些值。
这是我的模特
[Display(Name = "Type: "),
Required(ErrorMessage = "Required")]
public IEnumerable<SelectListItem> jobTitle { get; set; }
这是我的控制器
public void loadDropDown()
{
JobModel selectedJob = new JobModel();
reviewlogsEntities db = new reviewlogsEntities();
IEnumerable<SelectListItem> type = db.types.Select(m => new SelectListItem
{
Value = SqlFunctions.StringConvert((double)m.id),
Text = m.title
});
ViewBag.JobTitle = type;
}
[HttpGet]
public ActionResult DisplayJobTitle()
{
if (Request.IsAuthenticated)
{
loadDropDown();
return View();
}
else
{
return RedirectToAction("index", "home");
}
}
[HttpPost]
public ActionResult DisplayJobTitle(JobModel curJob)
{
loadDropDown();
if (ModelState.IsValid)
{
return View();
}
else
{
ModelState.AddModelError("", "Looks like there was an error with your job title, please make sure a job title is selected.");
}
return View();
}
最后,我的看法是这样的:
@Html.ValidationSummary(true, "Please try again.")
@using (Html.BeginForm())
{
@Html.LabelFor(model => model.type)
@Html.DropDownList("JobTitle")
<input class="submitButton" type="submit" value="Show Job Info" style="margin-left:126px;margin-bottom: 20px;" />
}
看到问题是我的模型中的变量jobTitle为空,因为我从不给它一个值,并且因为我没有给它一个值,所以表单认为它没有填写,因为它是必需的并且不会正确提交。我的问题是,提交表单时,如何将用户选择的任何职位的值返回给jobTitle变量,以免提交失败。
最佳答案
模型应接受所选值而不是项目集合:
[Display(Name = "Type: "),
Required(ErrorMessage = "Required")]
public int jobTitle { get; set; }