Asp.net-Mvc-2
MVC DropDownListFor - 驗證失敗後我必須手動重新填充選項嗎?
我有一個包含幾個屬性的視圖模型類。基本上,目前記錄(使用者正在編輯)和選項列表(用於使用 DropDownListFor 填充下拉列表)。
送出表單後,如果模型狀態無效,我將返回視圖。我知道表單是使用來自的“拒絕”輸入填充的
ModelState["name"].Value.AttemptedValue,但我不確定如何處理下拉列表的值列表。如果我什麼都不做,在驗證失敗並返回頁面時,我會收到“對象引用未設置為對象實例”錯誤,因為視圖模型的列表屬性為空。我知道它是空的,因為它沒有從表單發布中綁定,所以我可以在返回視圖之前從數據庫中重新填充它。
這是正確的方法嗎,還是我錯過了一種更明顯的方法來使下拉值持續存在?
是的,如果您打算在 POST 操作中返回相同的視圖,這是正確的方法:
- 從數據庫中綁定 GET 操作中的列表
- 渲染視圖
- 使用者將表單送出給 POST 操作
- 在此操作中,您僅獲取選定的值,因此如果模型無效並且您需要重新顯示視圖,您需要從數據庫中獲取列表以填充您的視圖模型。
以下是 MVC 中常用模式的範例:
public class HomeController : Controller { public ActionResult Index() { var model = new MyViewModel { Items = _repository.GetItems() }; return View(model); } [HttpPost] public ActionResult Index(MyViewModel model) { if (!ModelState.IsValid) { // Validation failed, fetch the list from the database // and redisplay the form model.Items = _repository.GetItems(); return View(model); } // at this stage the model is valid => // use the selected value from the dropdown _repository.DoSomething(model.SelectedValue); // You no longer need to fetch the list because // we are redirecting here return RedirectToAction("Success", "SomeOtherController"); } }