Frage

Das Problem ist: wenn ich lege 2 Kontrollen des gleichen Typs auf einer Seite, die ich verschiedene Präfixe für die Bindung angeben. In diesem Fall sind die Validierungsregeln erzeugen direkt nach der Form nicht korrekt. So, wie Client-Validierungsarbeiten für den Fall erhalten:?

Die Seite enthält:

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

die Steuerviewusercontrol :

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

wo Model.GetPrefixed("CountryCode") gerade gibt "FaxPhone.CountryCode" oder "PhonePhone.CountryCode" je nach Präfix


Und hier ist die Validierungsregeln erzeugt nach der Form. Sie sind für die Feldnamen „Phone.CountryCode“ dupliziert. Während das gewünschte Ergebnis ist 2 Regeln (erforderlich, die Anzahl) für jeden der die Feldnamen „FaxPhone.CountryCode“, „PhonePhone.CountryCode“ alt text http://www.freeimagehosting.net/uploads/37fbe720bf.png

Die Frage ist etwas Duplikat Asp.Net MVC2 Clientside Validierung und doppelte Problem der ID aber die Beratung manuell erzeugt ids hilft nicht.

War es hilfreich?

Lösung

Die korrekte Art und Weise die gleichen Präfixe zu setzen sowohl für Textbox und Validierung:

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

Dabei steht

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;
        }
    }
}

(zufällig fand die Lösung in dem Code auf Steve Sanderson Blog http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/ )

sieht auch wie Html.EditorFor Ansatz sollte auch funktionieren wie hier vorgeschlagen: ASP. NET MVC 2 - Ansichtsmodell Präfix

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top