【发布时间】:2010-03-31 22:06:23
【问题描述】:
我迷失在我正在从事的这个 MVC 项目上。我还阅读了布拉德威尔逊的文章。 http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html
我有这个:
public class Employee
{
[Required]
public int ID { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
}
这些在控制器中:
public ActionResult Edit(int id)
{
var emp = GetEmployee();
return View(emp);
}
[HttpPost]
public ActionResult Edit(int id, Employee empBack)
{
var emp = GetEmployee();
if (TryUpdateModel(emp,new string[] { "LastName"})) {
Response.Write("success");
}
return View(emp);
}
public Employee GetEmployee()
{
return new Employee {
FirstName = "Tom",
LastName = "Jim",
ID = 3
};
}
我的观点如下:
<% using (Html.BeginForm()) {%>
<%= Html.ValidationSummary() %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%= Html.LabelFor(model => model.FirstName) %>
</div>
<div class="editor-field">
<%= Html.DisplayFor(model => model.FirstName) %>
</div>
<div class="editor-label">
<%= Html.LabelFor(model => model.LastName) %>
</div>
<div class="editor-field">
<%= Html.TextBoxOrLabelFor(model => model.LastName, true)%>
<%= Html.ValidationMessageFor(model => model.LastName) %>
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
请注意,唯一可编辑的字段是姓氏。当我回发时,我会取回原来的员工并尝试使用 only LastName 属性对其进行更新。但是我在页面上看到的是以下错误:
•FirstName 字段是必需的。
据我了解,这是因为 TryUpdateModel 失败。但为什么?我告诉它只更新 LastName 属性。
我正在使用 MVC2 RTM
提前致谢。
【问题讨论】:
标签: asp.net asp.net-mvc asp.net-mvc-2