错误消息对所有字段显示相同的错误
本文关键字:错误 显示 消息 字段 | 更新日期: 2023-09-27 18:35:24
我的寄存器视图上的所有字段都收到相同的模型错误消息。这是我的注册发布方法的代码。
[CaptchaMvc.Attributes.CaptchaVerify("Captcha is not valid")]
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterRequest model)
{
if (ModelState.IsValid)
{
if (Membership_BAL.UsernameExist(model.UserName.Username))
{
ModelState.AddModelError("CustomError", "Usename is taken");
return View();
}
if (Membership_BAL.EmailExist(model.EmailAddress.EmailAddress))
{
ModelState.AddModelError("CustomError", "Email Address is taken");
return View();
}
if (
!Membership_BAL.CamparaEmailAddress(model.EmailAddress.EmailAddress,
model.EmailAddress.ComfirmEmailAddress))
{
ModelState.AddModelError("CustomError", "Email Address must match");
return View();
}
Membership_BAL.Register(model);
// TODO: Redirect use to profile page
return RedirectToAction("Index", "Home");
}
TempData["Message"] = "Error: captcha is not valid.";
return View();
}
这是视图
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<fieldset>
<legend> Register Form</legend>
<ol>
<li>
@Html.LabelFor(m => Model.UserName.Username)
@Html.EditorFor(m => Model.UserName.Username)
@Html.ValidationSummary()
</li>
<li>
@Html.LabelFor(m => Model.FirstName)
@Html.EditorFor(m => Model.FirstName)
</li>
<li>
@Html.LabelFor(m => Model.LastName)
@Html.EditorFor(m => Model.LastName)
</li>
<li>
@Html.LabelFor(m => Model.EmailAddress.EmailAddress)
@Html.EditorFor(m => Model.EmailAddress.EmailAddress)
@Html.ValidationSummary()
</li>
<li>
@Html.LabelFor(m => Model.EmailAddress.ComfirmEmailAddress)
@Html.EditorFor(m => Model.EmailAddress.ComfirmEmailAddress)
@Html.ValidationSummary()
</li>
<li>
@Html.MathCaptcha()
@TempData["Message"]
</li>
</ol>
<input type="submit" value="Register">
</fieldset>
}
没有看到视图或模型就很难安静,但我很确定它的问题与这条线有关
ModelState.AddModelError("CustomError", "Email Address must match");
此方法的第一个参数接收要显示错误的字段名称,我在您的操作中看到所有错误在字段中都具有相同的名称。
您应该更改此设置:
ModelState.AddModelError("CustomError", "Email Address must match");
为:
//Assuming that the field it's called Email
ModelState.AddModelError("Email", "Email Address must match");
模型中的每个元素以此类推
试试这个
if (ModelState.IsValid)
{
bool valid=true;
if (Membership_BAL.UsernameExist(model.UserName.Username))
{
ModelState.AddModelError("CustomError", "Usename is taken");
valid=false;
}
if (Membership_BAL.EmailExist(model.EmailAddress.EmailAddress))
{
ModelState.AddModelError("CustomError", "Email Address is taken");
valid=false;
}
if (
!Membership_BAL.CamparaEmailAddress(model.EmailAddress.EmailAddress,
model.EmailAddress.ComfirmEmailAddress))
{
ModelState.AddModelError("CustomError", "Email Address must match");
valid=false;
}
if (!valid)
{
return view();
}
Membership_BAL.Register(model);
// TODO: Redirect use to profile page
return RedirectToAction("Index", "Home");
}