我创建了一个编辑器模板,用于表示从动态下拉列表中进行选择,除了验证之外,它的工作原理是这样的,我一直无法弄清楚这一点。如果模型有 [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 是一个 Selector):

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

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

有帮助吗?

解决方案

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

其他提示

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

<%@ 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) %>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top