Question

J'essaie d'ajouter une validation simple à mon formulaire asp.net mvc et je ne parviens pas à obtenir la classe d'erreur .input-validation-error qui doit être ajoutée à mes entrées. La validation-summary-errors et .field-validation-error fonctionnent correctement. Merci d’avance pour votre aide!

Edit: Merci pour l'aide de tous !!! J'ai dû ajouter cette ligne au contrôleur pour éviter l'erreur:

ModelState.SetModelValue("txtEmailOrDealerID", collection.ToValueProvider()["txtEmailOrDealerID"]);

La vue:

<%using (Html.BeginForm("DealerLogin", "Home", FormMethod.Post))
  { %>
    <fieldset>
        <legend>Dealer Login</legend>
        <div class="row">
            <%=Html.Label("txtEmailOrDealerID", "E-Mail Or Dealer ID:")%>
            <%=Html.TextBox("txtEmailOrDealerID")%>
            <%=Html.ValidationMessage("txtEmailOrDealerID", "*")%>
        </div>
        <div class="row">
            <%=Html.Label("txtPassword", "Password:")%>
            <%=Html.Password("txtPassword")%>
            <%=Html.ValidationMessage("txtPassword", "*")%>
        </div>
        <div class="centerbutton">
            <input type="submit" id="btnSubmitDealer" value="Login"/>
        </div>
    </fieldset>
<%} %>

Le contrôleur:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DealerLogin(FormCollection collection)
{
    if (string.IsNullOrEmpty(collection["txtEmailOrDealerID"].Trim()))
        ModelState.AddModelError("txtEmailOrDealerID", "E-Mail Address or Dealer ID is required.");
    if (string.IsNullOrEmpty(collection["txtPassword"].Trim()))
        ModelState.AddModelError("txtPassword", "Password is required.");
    if (ModelState.IsValid)
        return Redirect("~/MyUploads");
    else
        return View("Index");
}

Le CSS:

/*Validation*/
.field-validation-error{color: #ff0000;}
.input-validation-error{border: 1px solid #ff0000; background-color: #ffeeee;}
.validation-summary-errors{color: #ff0000;}

La méthode d'extension HTML.Label:

public static string Label(this HtmlHelper helper, string forControl, string text)
{
    return String.Format("<label for='{0}'>{1}</label>", forControl, text);
}
Était-ce utile?

La solution

Du fond de ma tête, le paramètre id AddModelError doit correspondre à l'id de l'entrée. Donc, dans votre cas, cela devrait être changé en:

ModelState.AddModelError("txtEmailOrDealerID", "E-Mail Address or Dealer ID is required.");    
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top