gpt4 book ai didi

validation - 带有前缀的控件的 Asp.Net MVC2 客户端验证问题

转载 作者:行者123 更新时间:2023-12-03 09:54:30 30 4
gpt4 key购买 nike

问题是:当我在一个页面上放置 2 个相同类型的控件时,我需要指定不同的前缀进行绑定(bind)。在这种情况下,表单后生成的验证规则不正确。那么如何让客户验证这个案例呢?:

该页面包含:

<%
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 :
<%= 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”重复。虽然所需的结果是每个字段名称“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

关于validation - 带有前缀的控件的 Asp.Net MVC2 客户端验证问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2759167/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com