我已經創建了一個用於表示從動態下拉列表中進行選擇的編輯器模板,它的工作原理與應用除外,但我一直無法弄清楚。如果模型設置了[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>
我有點明白了,通過調用它的工作從這樣的看法(其中Category
是Selector
):
<%= Html.ValidationMessageFor(n => n.Category.SelectedId)%>
但它顯示驗證錯誤,因爲沒有提供正確的號碼,它不關心我是否設置Required
屬性。
你的權利,你的是一個很好的實現它的方法,但它沒有解決處理驗證邏輯的問題。 – 2010-03-30 13:12:31