2010-03-31 132 views
2

我迷失在我正在处理的这个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

在此先感谢。

回答

3

问题是,当您的表单被发回时,FirstName字段为空。问题在于,因为您将'员工'作为参数传递给您的操作,所以验证在您有机会致电GetEmployee()之前发生。您可以执行以下三件事之一:

1)从您的FirstName字段中删除[Required]属性。

2)添加Html.HiddenFor()此字段,以便它将使往返。就像这样:

<%= Html.HiddenFor(model => model.FirstName) %> 

3)改变你的行动声明:

public ActionResult Edit(int id, FormCollection form) 

(3)可能是你在找什么。

+0

这很有效!谢谢! – rkrauter 2010-03-31 23:21:24