Frage

Ich habe eine einfache Form auf einer Website ASP.NET MVC, dass ich baue. Diese Form vorgelegt wird, und dann bestätigen, dass ich die Formularfelder nicht null sind, leer oder falsch formatiert.

Allerdings, wenn ich ModelState.AddModelError() verwenden, um Validierungsfehler von meinem Controller-Code angeben, I eine Fehlermeldung erhalten, wenn meine Ansicht neu gerendert ist . In Visual Studio, ich, dass die folgende Zeile als die Position des Fehlers markiert:

<%=Html.TextBox("Email")%>

Der Fehler ist die folgende:

Nullreferenceexception durch Benutzercode unbehandelt wurde -. Objektverweis nicht auf eine Instanz eines Objekts festgelegt

Mein vollständiger Code für das Textfeld ist die folgende:

<p>
<label for="Email">Your Email:</label>
<%=Html.TextBox("Email")%>
<%=Html.ValidationMessage("Email", "*") %>
</p>

Hier ist, wie ich die Validierung in meinem Controller so machte:

        try
        {
            System.Net.Mail.MailAddress address = new System.Net.Mail.MailAddress(email);
        }
        catch
        {
            ModelState.AddModelError("Email", "Should not be empty or invalid");
        }

return View();

. Hinweis: dieses gilt für alle meine Felder , nicht nur meine E-Mail-Feld, solange sie sind ungültig

War es hilfreich?

Lösung

That's a horrible bug/feature (call in whatever) in ASP.NET MVC the helper that you may fix by calling SetModelValue like this:

ModelState.AddModelError("Email", "Should not be empty or invalid");
ModelState.SetModelValue("Email", new ValueProviderResult("raw value", "attempted value", CultureInfo.InvariantCulture));

By the way is there any reason you would write all this code when you could simply annotate your view model:

public class SomeViewModel
{
    [RegularExpression("Some bulletproof regex you could google to validate email address", ErrorMessage = "Should not be empty or invalid")]
    public string Email { get; set; }
}

and leave the data binder do the heavy lifting.

Andere Tipps

I am unable to reproduce.

Action

[HttpPost]
public ActionResult Index(string email)
{
    if (string.IsNullOrEmpty(email))
    {
        ModelState.AddModelError("Email", "Should not be empty or invalid");
    }
    return View();
}

View

    <%using (Html.BeginForm() { %>
    <p>
        <label for="Email">
            Your Email:</label>
        <%=Html.TextBox("Email")%>
        <%=Html.ValidationMessage("Email", "*") %>
        <input type="submit" />
    </p>
    <%} %>
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top