我迷失在我正在处理的这个MVC项目上。我还读过布拉德威尔森的文章。 http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html验证在ASP.NET MVC中触发
我有这样的:
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>
<% } %>
注意,只有现场编辑是姓氏。当我回发时,我找回原始员工并尝试使用更新 LastName属性。但是,我在页面上看到以下错误:
•FirstName字段是必需的。
这从我的理解,是因为TryUpdateModel失败。但为什么?我告诉它只更新姓氏属性。
我使用MVC2 RTM
在此先感谢。
这很有效!谢谢! – rkrauter 2010-03-31 23:21:24