加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 03:32:57 所属栏目:asp.Net 来源:网络整理
导读:问题是:当我在页面上放置2个相同类型的控件时,我需要为绑定指定不同的前缀.在这种情况下,在表单不正确之后生成的验证规则.那么如何让客户端验证工作呢? 该页面包含: % Html.RenderPartial(ViewLocations.Shared.PhoneEditPartial,new PhoneViewModel { Ph
问题是:当我在页面上放置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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读