Asp.net mvc 提交时查看MVC下拉列表为空
我对MVC上的下拉列表有问题。我找了又找,但没有结果 我的视图模型Asp.net mvc 提交时查看MVC下拉列表为空,asp.net-mvc,Asp.net Mvc,我对MVC上的下拉列表有问题。我找了又找,但没有结果 我的视图模型 public class IncidentFormViewModel { public Guid Guid { get; set; } public Incident Incident { get; set; } public Guid PersonInvolvedId { get; set; } public IEnumerable<Person> People { get;
public class IncidentFormViewModel
{
public Guid Guid { get; set; }
public Incident Incident { get; set; }
public Guid PersonInvolvedId { get; set; }
public IEnumerable<Person> People { get; set; }
}
和视图(我删除了无用的信息)
我做错了什么?这是在页面首次呈现时发生的,还是在您提交时发生的(顺便说一句,您的
LabelFor()
和ValidationMessageFor()
是用于不同的属性,因此是一个无意义的机器人)嗨,Stephen,页面加载很好,我得到了所有的“人”从加载到下拉框中的我的数据库中,只有在我提交时才会抛出此错误。因为您在返回视图时没有重新填充People
(因此为null
),并且作为旁注,视图模型不包含数据模型-它们包含您希望在视图中显示的事件
的属性(加上选项的IEnumerable
属性)在POST方法中,您需要执行model.People=unitofwork.Person.GetAll()
,就像在GET方法中执行的操作一样,当ModelState
无效并且返回视图时(建议您也阅读
public ActionResult New()
{
var incidentFormVM = new IncidentFormViewModel
{
Incident = new Incident(),
People = unitofwork.Person.GetAll()
};
return View("IncidentForm", incidentFormVM);
}
@using (Html.BeginForm("Save", "Incident"))
<div class="container">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
@Html.LabelFor(m => m.Incident.PersonInvolved)
@Html.DropDownListFor(m => m.PersonInvolvedId, new SelectList(Model.People, "Id", "FirstName"), new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Incident.PersonInvolved)
</div>
</div>
<br />
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
@Html.DropDownListFor(m => m.PersonInvolvedId, new SelectList(Model.People, "Id", "FirstName"), new { @class = "form-control" })