2010-03-30 113 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

相关问题