2011-04-22 20 views
1

可能重複:
mvc clientside validation for nested (collection) properties如何驗證ASP.NET MVC複雜實體框架模型中的單個集合項?

我有顯示領域形成與它的幾個EntityCollection對象複雜的實體框架模型的視圖。他們已經被證明是非常有問題的,因爲Set方法在模型綁定過程中不起作用,這在this stackoverflow question中描述(我的解決方案在答案中提供)。

現在我在使用EntityCollection中的TEntity類型的[Required] ValidationAttribute元數據進行必需的字段驗證時遇到問題。我認爲它的起源是因爲當你在類似Html.TextBoxFor(model => model.Application.References.ElementAt(i).FullName)(其中i是for循環中使用的int)的集合中使用強類型的Html Helpers時,呈現的輸出具有name="FullName"而不是name="Application.References[0].FullName"的輸入。那根本就不在元類的屬性上應用元數據。所以我的解決方案是使用像這樣的常規HTML助手:@Html.TextBox("Application.References[" + i + "].FullName", Model.Application.References.ElementAt(i).FullName)

現在,只有[Required]屬性創建的服務器端驗證有效。我可以獲得客戶端驗證的唯一方法是手動將data-val和data-val必需的屬性添加到呈現的輸入中,如下所示:@Html.TextBox("Application.References[" + i + "].FullName", Model.Application.References.ElementAt(i).FullName, new { data_val="true", data_val_required="The Full Name for Reference " + i + " is required."})。這似乎對我來說代碼太多了。當然有更好的方法來做到這一點?

下面是我對細節代碼摘錄:

EF型號

public class Application 
{ 
    //...EF framework code... 
    public EntityCollection<Reference> References 
    { 
     //get, set 
    } 
} 

public partial class Reference : EntityObject 
{ 
    public global::System.String FullName 
    { 
     //get, set 
    } 
} 

ReferenceMetaData.cs

[MetadataType(typeof(ReferenceMetadata))] 
public partial class Reference 
{ 
} 

public class ReferenceMetadata 
{ 
    [Required] 
    [DisplayFormat(NullDisplayText = "N/A")] 
    [DisplayName("Full Name")] 
    public string FullName { get; set; } 

    //...more properites 
} 

查看

@for (int i = 0; i < 3; i++) 
    { 
     @Html.ValidationMessage("Application.References[" + i + "].FullName") 
     <div class="input-container"> 
      <div class="editor-label"> 
       @Html.LabelFor(model => model.Application.References.ElementAt(i).FullName) 
      </div> 
      <div class="editor-field"> 
       @Html.TextBox("Application.References[" + i + "].FullName", Model.Application.References.ElementAt(i).FullName, new { maxlength = "100" }) 
      </div> 
     </div> 
     @* more view code...*@ 
    } 

此代碼沒有在@ Html.TextBox上手動設置data-val和data-val-required屬性。並稱,如下使客戶端驗證,但在不共享相同的驗證消息作爲默認的成本(或者任何我可能會在[Required(ErrorMessage = "Custom message")]元數據說明):

@for (int i = 0; i < 3; i++) 
    { 
     @Html.ValidationMessage("Application.References[" + i + "].FullName") 
     <div class="input-container"> 
      <div class="editor-label"> 
       @Html.LabelFor(model => model.Application.References.ElementAt(i).FullName) 
      </div> 
      <div class="editor-field"> 
       @Html.TextBox("Application.References[" + i + "].FullName", Model.Application.References.ElementAt(i).FullName, new { maxlength = "100", data_val="true", data_val_required="The Full Name for Reference " + i + " is required." }) 
      </div> 
     </div> 
     @* more view code...*@ 
    } 

回答