我迷失在我正在處理的這個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