【发布时间】:2013-01-07 07:50:33
【问题描述】:
非常基本的模型:
public class Person
{
public string Name;
public int Age;
}
和非常简单的视图:
@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>
}
还有一个非常简单的控制器:
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();
}
}
当屏幕加载时,值会正确绑定到页面。但是当我按下提交按钮时,人对象的年龄和姓名都为空值。
因为我使用了 Html.TextBoxFor,它不应该正确设置所有绑定并且对象应该自动绑定回 POST 吗?它在 GET 中绑定得很好..
我在调用 Html.BeginForm() 时是否遗漏了什么?
【问题讨论】:
-
你试过
EditorFor而不是TextBoxFor吗? -
另外,调试 post 方法时检查 Request.Form 里面的内容
-
设置为 EditorFor 在我尝试仅加载页面行时在第 3 行给出未处理的 NullReferenceException =( Type tModel = ViewData.ModelMetadata.ContainerType.GetProperty(ViewData.ModelMetadata.PropertyName).PropertyType;)
-
打开源视图并在页面中查找具有 id 或名称“姓名”和“年龄”的其他输入。有时你不小心有其他同名的输入,而 MVC 无法绑定,因为请求创建了一个包含这些值的集合。
-
我刚刚检查过,没有重复的输入标签。我确实发布了所有代码,我只是想让一个简单的示例正常工作
标签: c# asp.net-mvc razor