ASP NET MVC 3.0获取用户输入

时间:2011-01-25 13:12:00

标签: .net asp.net asp.net-mvc-3

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

2 个答案:

答案 0 :(得分:5)

编写视图模型:

public class UserViewModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

控制器:

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);
    }

}

查看:

@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" />
}

答案 1 :(得分:0)

例如,假设您的视图是使用“Person”类强列入的:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

然后在你的视图中:

@model MyMVCApp.Person
@using(Html.BeginForm())
{
    @Html.EditorForModel()
    // or Html.TextBoxFor(m => m.FirstName) .. and do this for all of the properties.
    <input type="submit" value="Submit" />
}

然后你会有一个处理表单的动作:

[HttpPost]
public ActionResult Edit(Person model)
{
    // do stuff with model here.
}

MVC使用所谓的ModelBinders来获取该表单集合并将其映射到模型。

要回答第二个问题,您可以使用以下JavaScript刷新页面:

<script type="text/javascript">
// Reload after 1 minute.
setTimeout(function ()
{
    window.location.reload();
}, 60000);
</script>