在我的更新操作中,我这样做:
[HttpPost]
public ActionResult Update()
{
if(Request.Form["..."])
{
}
..
}
所以我抓取实体的ID,然后加载它,然后根据发布的表单值更新属性。
我正在使用MVC2。
当我阅读模型状态但不确定如何开始时,我该怎么做呢?
我想重构这一点。
更新
我的viewmodel看起来像:
public class SomeViewModel
{
public User User {get; set;}
}
答案 0 :(得分:6)
您应该定义一个视图模型,其中包含视图将发送的所有必要信息:
public class MyViewModel
{
public int Foo { get; set; }
[Required]
public string Bar { get; set; }
[Required]
public DateTime? Baz { get; set; }
}
然后让控制器操作将此视图模型作为参数:
[HttpPost]
public ActionResult Update(MyViewModel model)
{
if (!ModelState.IsValid)
{
// validation failed (the user left the Bar field empty) =>
// we redisplay the view so that he can fix the errors
return View(model);
}
// at this stage we know that the model is valid =>
// we could do some processing. The model.Foo and model.Bar
// properties will contain the values entered by the user in the
// corresponding form fields so that you don't need to fetch them
// manually from the Request. The default model binder will take
// care of this
...
}