你可以很简单地完成它:
第一步:例如,在模型中,你有一个名为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)
{
}
(m => m.FirstName)
,而视图和控制器中有@Html.TextBox("name")
。Html.TextBox 中的 "name" 是否需要与 UserModel 变量匹配?如果不是,这些页面值如何映射到正确的对象属性? - user153923