我有一个由患者对象和访问集合组成的视图模型。视图模型填充了所有正确的属性值,并且属性在编辑视图中正确显示。在将模型传递给控制器的编辑 (GET) 操作中的视图之前,我还验证了视图模型中的属性值。
问题是,即使我在编辑视图中没有更改任何属性,绑定到下拉列表(性别和条件)的属性也不会传递回控制器的编辑(POST)操作。这会导致抛出异常。
这些属性具有值,但在某个地方它们会丢失。我该如何解决这个问题?
ASP.NET MVC 4 RC
public ActionResult Edit(int id = 0)
{
var patient = this.db.Patients.Where(p => p.Id == id).FirstOrDefault();
var visits = this.db.Visits.Where(v => v.PatientId == patient.Id && v.IsActive).OrderByDescending(v => v.VisitDate);
PatientEditViewModel model = new PatientEditViewModel();
model.Patient = patient;
model.Visits = visits;
if (patient == null)
{
return this.HttpNotFound();
}
ViewBag.GenderId = new SelectList(this.db.Genders, "Id", "Name", patient.GenderId);
ViewBag.HandednessId = new SelectList(this.db.Handednesses, "Id", "Name", patient.HandednessId);
return this.View(model);
}
[HttpPost]
public ActionResult Edit(PatientEditViewModel model)
{
Mapper.CreateMap<PatientEditViewModel, Patient>();
var entity = Mapper.Map<PatientEditViewModel, Patient>(model);
if (ModelState.IsValid)
{
this.db.Entry(entity).State = EntityState.Modified;
this.db.SaveChanges();
}
this.ViewBag.GenderId = new SelectList(this.db.Genders, "Id", "Name", entity.GenderId);
this.ViewBag.HandednessId = new SelectList(this.db.Handednesses, "Id", "Name", entity.HandednessId);
return this.View(model);
}
@model Web.Models.PatientEditViewModel
@{
ViewBag.Title = "XXX";
}
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Patient</legend>
@Html.HiddenFor(model => model.Patient.Id)
<div class="editor-label">
@Html.LabelFor(model => model.Patient.GenderId, "Gender")
</div>
<div class="editor-field">
@Html.DropDownFor("GenderId", String.Empty)
@Html.ValidationMessageFor(model => model.Patient.GenderId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Patient.HandednessId, "Handedness")
</div>
<div class="editor-field">
@Html.DropDownFor("HandednessId", String.Empty)
@Html.ValidationMessageFor(model => model.Patient.HandednessId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Patient.Comments)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Patient.Comments)
@Html.ValidationMessageFor(model => model.Patient.Comments)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
@Html.Partial("_CurrentAndPreviousVisits", Model.Visits)
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}