问题是:当我在页面上放置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&lt; PhoneViewModel&gt;:
<%= 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并没有帮助。
答案 0 :(得分:10)
为文本框和验证设置相同前缀的正确方法:
<% 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;
}
}
}
(偶然在Steve Sanderson的博客http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/上的代码中找到了解决方案)
看起来Html.EditorFor方法也应该像以下建议一样工作:ASP.NET MVC 2 - ViewModel Prefix