dfe*_*aro 3 c# asp.net-mvc razor
非常基本的型号:
public class Person
{
public string Name;
public int Age;
}
Run Code Online (Sandbox Code Playgroud)
而且非常简单的观点:
@model DynWebPOC.Models.Person
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
Hello, @Model.Name
<br/>
You're getting old at @Model.Age years old now!
@using(Html.BeginForm("Index","Test",FormMethod.Post))
{
<fieldset>
<label for="name" style="color: whitesmoke">Name:</label>
@Html.TextBoxFor(m => m.Name)
<br/>
<label for="age" style="color: whitesmoke">Age:</label>
@Html.TextBoxFor(m => m.Age)
<br/>
<input type="submit" value="Submit"/>
</fieldset>
}
Run Code Online (Sandbox Code Playgroud)
一个非常简单的控制器:
public class TestController : Controller
{
[HttpGet]
public ActionResult Index()
{
object model = new Person {Name = "foo", Age = 44};
return View(model);
}
[HttpPost]
public ActionResult Index(Person person)
{
return View();
}
}
Run Code Online (Sandbox Code Playgroud)
加载屏幕时,值正确绑定到页面.但是当我按下提交按钮时,person对象具有age和name的所有空值.
因为我使用了Html.TextBoxFor,它不应该正确设置所有绑定并且对象应该自动绑定回POST吗?它在GET中绑定得很好..
我在Html.BeginForm()的调用中错过了什么?
您必须在模型中创建属性
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
代替
public class Person
{
public string Name;
public int Age;
}
Run Code Online (Sandbox Code Playgroud)
ASP.net MVC仅绑定属性.