代码之家  ›  专栏  ›  技术社区  ›  Jon

.未将输入验证错误类添加到视图中的输入中

  •  1
  • Jon  · 技术社区  · 15 年前

    我正在尝试向ASP.NET MVC窗体添加一些简单的验证,但在获取要添加到输入中的.input验证错误类时遇到问题。验证摘要错误和.field验证错误工作正常。提前感谢您的帮助!

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

    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 回复  |  直到 12 年前
        1
  •  2
  •   Razzie    15 年前

    从我的头上看,addModelErrorID参数应该与输入的ID匹配。因此,在您的情况下,应该将其更改为:

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