2010-03-30 71 views
0

我已經創建了一個用於表示從動態下拉列表中進行選擇的編輯器模板,它的工作原理與應用除外,但我一直無法弄清楚。如果模型設置了[Required]屬性,那麼如果選擇默認選項,我希望該屬性無效。如何驗證ASP.NET MVC編輯器模板中的結果?

必須表示爲下拉列表是Selector視圖模型對象:

public class Selector 
{ 
    public int SelectedId { get; set; } 
    public IEnumerable<Pair<int, string>> Choices { get; private set; } 
    public string DefaultValue { get; set; } 

    public Selector() 
    { 
     //For binding the object on Post 
    } 

    public Selector(IEnumerable<Pair<int, string>> choices, string defaultValue) 
    { 
     DefaultValue = defaultValue; 
     Choices = choices; 
    } 
} 

編輯模板看起來是這樣的:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> 
<select class="template-selector" id="<%= ViewData.ModelMetadata.PropertyName %>.SelectedId" name="<%= ViewData.ModelMetadata.PropertyName %>.SelectedId"> 
<% 
    var model = ViewData.ModelMetadata.Model as QASW.Web.Mvc.Selector; 
    if (model != null) 
    { 
      %> 
    <option><%= model.DefaultValue %></option><% 
     foreach (var choice in model.Choices) 
     { 
      %> 
    <option value="<%= choice.Value1 %>"><%= choice.Value2 %></option><% 
     } 
    } 
    %> 
</select> 

我有點明白了,通過調用它的工作從這樣的看法(其中CategorySelector):

<%= Html.ValidationMessageFor(n => n.Category.SelectedId)%> 

但它顯示驗證錯誤,因爲沒有提供正確的號碼,它不關心我是否設置Required屬性。

回答

2

我找到了一個解決方案,使用自定義驗證規則對隱藏字段進行驗證,here。使用此方法,您可以輕鬆地將自定義驗證添加到任意類型。

0

爲什麼您的編輯器模板不是強類型的?

<%@ Control Language="C#" 
    Inherits="System.Web.Mvc.ViewUserControl<QASW.Web.Mvc.Selector>" %> 

爲什麼不使用DropDownListFor幫手:

<%= Html.DropDownListFor(
    x => x.SelectedId, 
    new SelectList(Model.Choices, "Value1", "Value2") 
)%> 

爲了避免魔術字符串,你可以一個ChoicesList屬性添加到您的視圖模型:

public IEnumerable<SelectListItem> ChoicesList 
{ 
    get 
    { 
     return Choices.Select(x => new SelectListItem 
     { 
      Value = x.Value1.ToString(), 
      Text = x.Value2 
     }); 
    } 
} 

和你的助手綁定到它:

<%= Html.DropDownListFor(x => x.SelectedId, Model.ChoicesList) %> 
+0

你的權利,你的是一個很好的實現它的方法,但它沒有解決處理驗證邏輯的問題。 – 2010-03-30 13:12:31