.input-validation-error类未添加到视图中的输入

时间:2009-09-14 14:24:16

标签: c# asp.net-mvc validation html-helper

我正在尝试为我的asp.net mvc表单添加一些简单的验证,并且无法将.input-validation-error类添加到我的输入中。 validation-summary-errors和.field-validation-error工作正常。在此先感谢您的帮助!

编辑:感谢大家的帮助!!!我必须将此行添加到控制器以避免错误:

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

观点:

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

控制器:

[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");
}

CSS:

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

HTML.Label扩展方法:

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

1 个答案:

答案 0 :(得分:2)

从我的脑海中,AddModelError id参数应该与输入的id匹配。所以在你的情况下,它应该改为:

ModelState.AddModelError("txtEmailOrDealerID", "E-Mail Address or Dealer ID is required.");