我有一個基於ViewModel的表單,它提示用戶將Person的XApplication
狀態更改爲Accepted或Rejected。HttpGet和HttpPost返回驗證錯誤並加載SelectList
當我通過POST提交表單時,我想創建一個新的XApplication
,然後如果成功將用戶帶回同一頁面。如果它包含錯誤,我希望再次通過傳遞View(personApp)
重新載入表單,這將通過剃刀方法@Html.ValidationSummary()
顯示錯誤。
但是,當我嘗試這樣做時,View()不知道我的SelectLists,並且無法使用「應用程序已接受」和「應用程序已拒絕」填充下拉列表。
我可以採取另一種方法嗎?
[Route("student/xApplication/{personId?}")]
[HttpGet]
public ActionResult xApplication(int? personId)
{
if (personId == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Person person = db.People.Find(personId);
if (person == null)
{
return HttpNotFound();
}
// Prepare ViewModel to pass to view, based on personId
PersonViewModel personVModel = new PersonViewModel();
personVModel.Person = person;
// Get XApplication Data
var xApps = from a in db.XApplications where a.personId == personId select a;
XApplication personXApplication = null;
if (xApps.Count() > 0)
{
personXApplication = xApps.First();
}
personVModel.XApplications = personXApplication;
List<SelectListItem> applicationStatusItems = new List<SelectListItem>();
applicationStatusItems.Add(new SelectListItem { Value = "1", Text = "Application Accepted" });
applicationStatusItems.Add(new SelectListItem { Value = "0", Text = "Application Rejected" });
SelectList applicationStatusList = new SelectList(applicationStatusItems, "Value", "Text", null);
personVModel.ApplicationStatusList = applicationStatusList;
return View(personVModel);
}
[HttpPost]
[Route("student/xApplication")]
public ActionResult xApplication(PersonViewModel personVModel)
{
if (ModelState.IsValid)// Checks no errors
{
db.XApplications.Add(personVModel.XApplications);
db.SaveChanges();
return Redirect("/student/xApplication/" + personVModel.Person.id);
}
return View(personVModel);
}
你可以做的是讓視圖模型自己照顧selectlistitem。因此,您不必重新填充控制器中的項目。 – Jamie 2014-09-26 14:50:36
我會給那一個去傑米,是有道理的。 – 2014-09-26 15:07:14