我有一個包含患者對象和訪問集合的視圖模型。視圖模型將填充所有正確的屬性值,並且屬性將在編輯視圖中正確顯示。在將模型傳遞給控制器的「編輯」(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")
}
請將相關代碼發送給我們 – 2012-07-16 17:58:17
向我們展示獲取操作,發佈操作和查看的代碼 – archil 2012-07-16 17:58:27
用代碼更新的問題... – user1469655 2012-07-16 18:05:38