使用 POST 将 ViewModel 发送回控制器

tac*_*cos 2 c# asp.net-mvc post model-binding asp.net-mvc-4

对于 MVC4,通过 将ViewModel用于填充视图的视图发送回控制器的最佳实践方法是POST什么?

Hen*_*ema 5

让我们假设你想要一个带有这个视图模型的登录表单:

public class LoginModel
{
    [Required]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    public bool RememberMe { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在视图中使用这个视图模型很简单,只需向LoginModel视图发送一个新实例:

public ActionResult Login()
{
    var model = new LoginModel();
    return View(model);
}
Run Code Online (Sandbox Code Playgroud)

现在我们可以创建Login.cshtml视图:

@model App.Models.LoginModel

@using (Html.BeginForm())
{
    @Html.LabelFor(model => model.UserName)
    @Html.TextBoxFor(model => model.UserName)
    @Html.ValidationMessageFor(model => model.UserName)

    @Html.LabelFor(model => model.Password)
    @Html.PasswordFor(model => model.Password)
    @Html.ValidationMessageFor(model => model.Password)

    @Html.CheckboxFor(model => model.RememberMe)
    @Html.LabelFor(model => model.RememberMe)

    <input type="submit" value="Login" />
}
Run Code Online (Sandbox Code Playgroud)

现在我们必须在控制器中创建一个动作来处理这个表单的帖子。我们可以这样做:

[HttpPost]
public ActionResult Login(LoginModel model)
{
    if (ModelState.IsValid)
    {
        // Authenticate the user with information in LoginModel.
    }

    // Something went wrong, redisplay view with the model.
    return View(model);
}
Run Code Online (Sandbox Code Playgroud)

HttpPost属性将确保控制器操作只能通过发布请求到达。

MVC 将使用它的魔法并将视图中的所有属性绑定回一个LoginModel用帖子中的值填充的实例。