你可以这样做很简单:
第一:例如在模型中你有 User.cs 这个实现
public class User
{
public string username { get; set; }
public string age { get; set; }
}
我们将空模型传递给用户——当他像这样提交表单时,这个模型将填充用户的数据
public ActionResult Add()
{
var model = new User();
return View(model);
}
当您将空用户的视图作为模型返回时,它会映射到您实现的表单的结构。我们在 HTML 方面有这个:
@model MyApp.Models.Student
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Student</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.username, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.username, new {
htmlAttributes = new { @class = "form-
control" } })
@Html.ValidationMessageFor(model => model.userame, "",
new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.age, htmlAttributes: new { @class
= "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.age, new { htmlAttributes =
new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.age, "", new {
@class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default"
/>
</div>
</div>
</div>
}
所以在按钮提交上你会像这样使用它
[HttpPost]
public ActionResult Add(User user)
{
// now user.username has the value that user entered on form
}