嗨,我有一个带有特定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变量,以便不会出现提交失败。
发布于 2016-01-15 23:50:58
模型应接受选定的值,而不是项的集合:
[Display(Name = "Type: "),
Required(ErrorMessage = "Required")]
public int jobTitle { get; set; }发布于 2016-01-15 23:55:26
您需要一个属性来映射模型中的选定值,如下所示:
[Display(Name = "Type: "),
Required(ErrorMessage = "Required")]
public int SelectedjobTitle { get; set; }然后在您的视图中:
@Html.DropDownList("SelectedJobTitle",ViewBag.JobTile as IEnumerable<SelectListItem>)发布于 2016-01-16 00:00:48
如下所示使用DropDownListFor:
@Html.DropDownListFor(model => model.JobTitle, Model.Jobs)在您的模型上:
[Display(Name = "Type: "),
Required(ErrorMessage = "Required")]
public int JobTitle { get; set; }
public IEnumerable<SelectListItem> Jobs { get; set; } 别忘了在你的控制器上填写“工作”。
https://stackoverflow.com/questions/34814742
复制相似问题