我有一个viewmodel类,它包含几个属性.基本上,当前记录(用户正在编辑)和一个选项列表(用于使用DropDownListFor填充下拉列表).
提交表单后,如果modelstate无效,则返回视图.我知道表单是使用"拒绝"输入填充的ModelState["name"].Value.AttemptedValue,但我不知道如何处理下拉列表的值列表.
如果我什么都不做,在验证失败并返回页面时,我得到一个'对象引用未设置为对象的实例'错误,因为viewmodel的list属性为null.我知道它是null,因为它没有从表单帖子绑定,所以我可以在返回视图之前从数据库重新填充它.
这是正确的方法,还是我错过了一种更明显的方法来使下拉值保持不变?
Dar*_*rov 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");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2159 次 |
| 最近记录: |