2010-11-14 61 views
7

我有一个viewmodel类,其中包含几个属性。基本上,当前记录(用户正在编辑)和选项列表(用于使用DropDownListFor填充下拉列表)。MVC DropDownListFor - 我必须在验证失败后手动重新填充选项吗?

表单提交后,如果modelstate无效,我会返回到视图。我知道该表单使用来自ModelState["name"].Value.AttemptedValue的“被拒绝”输入来填充,但我不确定如何处理下拉列表的值列表。

如果我什么都不做,在验证失败并返回页面时,由于viewmodel的列表属性为空,我得到'对象引用未设置为对象的实例'错误。我知道它是空的,因为它没有绑定到表单文章,所以我可以在返回到视图之前从数据库重新填充它。

这是正确的方式去了解它,还是我错过了更明显的方式使下拉值持续?

回答

10

是的,这是正确的方式,如果你打算返回相同的观点在POST操作:

  1. 绑定从数据库
  2. 的列表中获取动作渲染视图
  3. 用户提交POST操作中的POST动作
  4. 您只能提取选定的值,因此如果模型无效且您需要重新显示视图,则需要从数据库中取回列表以填充视图模型。

这里有一个常用模式的例子在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"); 
    } 
} 
+0

谢谢。这几乎是我使用的技术。只需使用新技术就我自己的项目开展工作,对第二种意见进行检查是很好的! – Gavin 2010-11-15 20:32:59

0

您可以使用XHR调用Ajax提交您的数据,而不是通过提交其默认提交按钮的形式。

这种技术的优点是你不需要重新填充你的列表。

在客户端和Ajax调用回来后,你可以在status值决定做你想做什么都用支票

$.ajax({ 
    url: '@Url.Action("Index", "Controller")', 
    data: $("#form").serialize(), 
    type: 'POST', 
    success: function (data) { 
     if (data.status == "Successful") { 
      // you can redirect to another page by window.location.replace('New URL') 
     } else { 
      // you can display validation message 
     } 
    } 
}); 

您ActionMethod会像:

[HttpPost] 
     public JsonResult Index() 
     { 
      if (ModelState.IsValid) 
      { 
       return Json(new { status = "Success" });  
      } 
      else 
      { 
       return Json(new { status = "Fail" }); 
      } 
     } 
相关问题