ASP NET MVC 3.0获取用户输入

Vik*_*ice 0 .net asp.net asp.net-mvc-3

什么是从视图到控制器获取用户输入的最佳方法.我的意思是特定输入不像"FormCollection"那样像"对象人"或"int值"以及如何在特定间隔刷新页面

Dar*_*rov 5

通过编写视图模型:

public class UserViewModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

控制器:

public class UsersController : Controller
{
    public ActionResult Index()
    {
        return View(new UserViewModel());
    }

    [HttpPost]
    public ActionResult Index(UserViewModel model)
    {
        // Here the default model binder will automatically
        // instantiate the UserViewModel filled with the values
        // coming from the form POST
        return View(model);
    }

}
Run Code Online (Sandbox Code Playgroud)

视图:

@model AppName.Models.UserViewModel
@using (Html.BeginForm())
{
    <div>
        @Html.LabelFor(x => x.FirstName)
        @Html.TextBoxFor(x => x.FirstName)
    </div>
    <div>
        @Html.LabelFor(x => x.LastName)
        @Html.TextBoxFor(x => x.LastName)
    </div>

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