代码之家  ›  专栏  ›  技术社区  ›  Morten Christiansen

如何在ASP.NET MVC编辑器模板中验证结果?

  •  0
  • Morten Christiansen  · 技术社区  · 15 年前

    我已经创建了一个编辑器模板,用于表示从动态下拉列表中进行选择,它的工作方式和它应该的一样,除了验证之外,我还没有弄清楚。如果模型有 [Required] 属性集,如果选择了默认选项,我希望它失效。

    必须表示为下拉列表的视图模型对象是 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 是一个 选择器 ):

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

    但它显示验证错误,因为没有提供正确的数字,它不关心我是否设置了 Required 属性。

    2 回复  |  直到 15 年前
        1
  •  2
  •   Morten Christiansen    15 年前

    我找到了一个解决方案,使用自定义验证规则对隐藏字段进行验证, here . 使用这种方法,您可以轻松地向任意类型添加自定义验证。

        2
  •  0
  •   Darin Dimitrov    15 年前

    为什么您的编辑器模板不是强类型的?

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

    为什么不使用DropDownListfor帮助程序:

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

    要避免使用魔法字符串,可以将ChoiceList属性添加到视图模型中:

    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) %>