我有一个包含几个属性的viewmodel类。基本上,当前记录(用户正在编辑)和一个选项列表(用于使用DropDownListFor填充下拉列表)。
提交表单后,如果modelstate无效,我将返回视图。我了解表单是使用ModelState["name"].Value.AttemptedValue
的“已拒绝”输入填充的,但我不确定如何处理下拉列表的值列表。
如果我什么也不做,在验证失败并返回页面时,我得到一个'对象引用未设置为对象的实例'错误,因为viewmodel的list属性为null。我知道它是null,因为它没有从表单帖子绑定,所以我可以在返回视图之前从数据库重新填充它。
这是正确的方法,还是我错过了一种更明显的方法来保持下拉值?
答案 0 :(得分:10)
是的,如果您打算在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");
}
}
答案 1 :(得分: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" });
}
}