我已经创建了一个用于表示从动态下拉列表中进行选择的编辑器模板,它的工作原理与应用除外,但我一直无法弄清楚。如果模型设置了[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