ASP.NET MVC2客户端验证问题带有前缀的控件
-
02-10-2019 - |
题
问题是:当我将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" });
%>
控制视图u003CPhoneViewModel>:
<%= 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”或“ phone Phone.countrycode”,具体取决于前缀
这是表格之后生成的验证规则。它们以“ phone.countrycode”字段名称重复。虽然所需的结果是每个字段名称“ Faxphone.countrycode”,“ Phone Phone.CountryCode”的2个规则(必需的数字)虽然是2个规则(必需的编号)。Alt Text http://www.freeimagehosting.net/uploads/37fbe720bf.png
这个问题有些重复 ASP.NET MVC2客户端验证和重复ID的问题但是,手动生成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;
}
}
}
看起来HTML.Editor方法应尽其所能,并在此处建议: ASP.NET MVC 2 -ViewModel前缀
不隶属于 StackOverflow