在构建视图模型时,我倾向于遵循 CQRS 模型。所有的渲染都是用ViewModel
类完成的,所有的回发都是用Command
类完成的。这是一个人为的例子。假设我们有一个用于创建用户的小表单视图。
和ViewModel
类Command
看起来像这样:
public abstract class ViewModel {}
public abstract class Command: ViewModel
public class CreateUserViewModel : ViewModel
{
public string Username { get; set; }
public string Password { get; set; }
public string PasswordConfirm { get; set; }
}
public class CreateUserCommand : Command
{
public string Username { get; set; }
public string Password { get; set; }
public string PasswordConfirm { get; set; }
}
UserController
创建 aCreateUserViewModel
作为请求的模型,并Get
期望CreateUserCommand
请求a Post
:
public ActionResult CreateUser()
{
// this should be created by a factory of some sort that is injected in
var model = new CreateUserViewModel();
return View(model);
}
[HttpPost]
public ActionResult CreateUser(CreateUserCommand command)
{
// validate and then save the user, create new CreateUserViewModel and re-display the view if validation fails
}
模型绑定负责确保CreateUserCommand
正确填充 Posted 的属性,即使 Get View 绑定到CreateUserViewModel
.