2009-09-12 40 views
1

您好,我在我的應用程序中有以下鱈魚,但只有兩個領域它不工作。MVC數據註釋 - 必填字段不工作

[Required]   
public string DevelopmentPM { get; set; } 

下面的測試運行,並通過:

[TestMethod] 
    public void SiteConstruction_MODEL_DevelopmentPM_Is_Required() 
    { 
     //arrange 
     var propertyInfo = typeof(SiteConstructionMetadata).GetProperty  
          ("DevelopmentPM"); 

     //act 
     var attribute = propertyInfo.GetCustomAttributes(typeof(RequiredAttribute), 
         true).Cast<RequiredAttribute>().FirstOrDefault(); 

     //assert 
     Assert.IsNotNull(attribute); 
    } 

我controlller樣子:

 TryUpdateModel(siteConstruction); 

     if (!ModelState.IsValid) 
      return View(siteConstruction); 

我在模型中其他必填字段,他們都OK。這個字段爲空(我檢查),但不會使模型無效 - 所以沒有驗證和保存錯誤。

我查看

<li> 
     <label for="DevelopmentPM"> 
      <strong>Development PM:</strong></label> 
     <%= Html.TextBox("DevelopmentPM") %> 
     <%= Html.ValidationMessage("DevelopmentPM", "*") %> 
    </li> 

我看着我的.dbml(LINQ到SQL),拼寫看起來確定。

我很想念一件簡單的事 - 拜託,生氣了。

感謝

戴維

回答

1

[MetadataType(typeof(SiteConstructionMetadata))]在我的部分類上面,我認爲它是理所當然的。

下一次,我想我會發布所有內容 - 而不是發佈片段 - 很快就會發現這個問題。

Davy

0

確保您做出DataAnnotationsModelBinder默認模式粘結劑了。添加在您的Global.asax.cs如下:

ModelBinders.Binders.DefaultBinder = new Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder(); 

,並確保你已經在你的項目中引用的System.ComponentModel.DataAnnotations.dll組裝。有關更多詳細信息,請參閱this tutorial

+0

謝謝 - 不,我有 - 就像我說的 - 這個確切的代碼在別處工作。 我已經調試過,即使我在控制器中顯式設置thge字段爲null - 模型仍然有效。 – Davy 2009-09-12 22:54:13