【发布时间】:2016-06-18 14:03:47
【问题描述】:
我无法获取用户名和密码的错误消息。我只为密码字段而不是两者都收到验证错误,如果我通过删除密码字段来测试它,那么我会看到用户名字段是必需的错误。不知道是什么问题。以下是它的代码。在我的模型类中的这些字段上具有必需的属性。下面给出了视图和控制器代码。
<div class="xmp-form xmp-Contactus container MarginCustom">
<p class="greyfontmod">
Both username and password are <b>case-sensitive.</b>
</p>
<div class="span4" style="margin: 0 auto;float:none">
@using (Html.BeginForm("Submit", "Home", FormMethod.Post))
{
<div class="xmp-form-row">
<label class="xmp-form-label">Username</label>
@Html.TextBoxFor(m => m.UserID, new { @class = "xmp-textbox" })
@Html.ValidationMessageFor(x => x.UserID, " ", new { @class = "greyfontMedError" })
<span class="xmp-validation" style="display:none;">**</span>
</div>
<div class="xmp-form-row">
<label class="xmp-form-label">Password</label>
@Html.PasswordFor(m => m.Password, new { @class = "xmp-Login" })
@Html.ValidationMessageFor(x => x.Password, "", new { @class = "greyfontMedError" })
<span class="xmp-validation" style="display:none;">**</span>
</div>
<p class="greyfontmod">
<b>Note: After 3 unsuccessful attempts your account will be blocked</b>
</p>
<div class="xmp-form-row" style="text-align:center;">
<input type="submit" name="submitBtn" value="SUBMIT" />
</div>
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
}
<div class="xmp-form-row" style="text-align:center">
<p class="greyfontmod">
@Html.ActionLink("Forgot Username/Password?", "ResetPassword", "Home", null, new { @class = "Link" })
</p>
</a>
</div>
</div>
控制器
/// <summary>
/// Logins this instance.
/// </summary>
/// <returns>ActionResult</returns>
public ActionResult Submit(CustomerModel customerModel)
{
sessionHelper = new SessionHelper();
if (ModelState.IsValidField("Username") && (ModelState.IsValidField("Password")))
{
customerModel = sessionHelper.ValidateLogin(customerModel);
if (customerModel.BorrowerSeqNo == -1)
{
ModelState.AddModelError("Error", "Invalid Username/Password");
return View("Login", customerModel);
}
return View("AccountStatus", customerModel);
}
else
{
return View("Login", customerModel);
}
}
在下面添加我的 customerModel 类。
public class CustomerModel
{
/// <summary>
/// Gets or sets the user identifier.
/// </summary>
/// <value>The user identifier.</value>
[Required]
public string UserID { get; set; }
/// <summary>
/// Gets or sets the password.
/// </summary>
/// <value>The password.</value>
[Required]
public string Password { get; set; }
/// <summary>
/// Gets or sets the ip address.
/// </summary>
/// <value>The ip address.</value>
【问题讨论】:
-
你也可以分享你的 CustomerModel 类吗? UserID/UserName 属性可能没有设置正确的验证属性。
-
我没有尝试过,但看起来代码应该可以工作。您可以尝试调试并检查表达式“ModelState.IsValidField("Password")”的值。如果这按预期工作,则检查 DOM 并查看错误是否正在呈现但由于某些样式等原因不可见。