微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

具有前缀的控件的Asp.Net MVC2 Clientside验证问题

问题是:当我在页面上放置2个相同类型的控件时,我需要为绑定指定不同的前缀.在这种情况下,在表单不正确之后生成的验证规则.那么如何让客户端验证工作呢?

页面包含:

<%
    Html.RenderPartial(ViewLocations.Shared.PhoneEditPartial,new Phoneviewmodel { Phone = person.PhonePhone,Prefix = "PhonePhone" });
    Html.RenderPartial(ViewLocations.Shared.PhoneEditPartial,new Phoneviewmodel { Phone = person.FaxPhone,Prefix = "FaxPhone" });
%>

控件ViewUserControl< Phoneviewmodel>:

<%= Html.TextBox(Model.GetPrefixed("CountryCode"),Model.Phone.CountryCode) %>
<%= Html.ValidationMessage("Phone.CountryCode",new { id = Model.GetPrefixed("CountryCode"),name = Model.GetPrefixed("CountryCode") })%>

其中Model.GetPrefixed(“CountryCode”)只返回“FaxPhone.CountryCode”或“PhonePhone.CountryCode”,具体取决于前缀

这是表单后生成的验证规则.它们被复制为字段名“Phone.CountryCode”.虽然所需的结果是每个FieldNames“FaxPhone.CountryCode”,“PhonePhone.CountryCode”的2个规则(必需,数量)
alt text http://www.freeimagehosting.net/uploads/37fbe720bf.png

这个问题与Asp.Net MVC2 Clientside Validation and duplicate ID’s problem有些重复
但建议手动生成ID并没有帮助.

解决方法

为文本框和验证设置相同前缀的正确方法

<% using (Html.BeginHtmlFieldPrefixScope(Model.Prefix)) { %>
   <%= Html.TextBoxFor(m => m.Address.PostCode) %>
   <%= Html.ValidationMessageFor(m => m.Address.PostCode) %>
<% } %>

哪里

public static class HtmlPrefixScopeExtensions
{
    public static Idisposable BeginHtmlFieldPrefixScope(this HtmlHelper html,string htmlFieldPrefix)
    {
        return new HtmlFieldPrefixScope(html.ViewData.TemplateInfo,htmlFieldPrefix);
    }

    private class HtmlFieldPrefixScope : Idisposable
    {
        private readonly TemplateInfo templateInfo;
        private readonly string prevIoUsHtmlFieldPrefix;

        public HtmlFieldPrefixScope(TemplateInfo templateInfo,string htmlFieldPrefix)
        {
            this.templateInfo = templateInfo;

            prevIoUsHtmlFieldPrefix = templateInfo.HtmlFieldPrefix;
            templateInfo.HtmlFieldPrefix = htmlFieldPrefix;
        }

        public void dispose()
        {
            templateInfo.HtmlFieldPrefix = prevIoUsHtmlFieldPrefix;
        }
    }
}

(偶然在史蒂夫桑德森的博客http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/代码中找到了解决方案)

看起来像Html.EditorFor方法应该像这里建议的那样工作:ASP.NET MVC 2 – ViewModel Prefix

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐