最佳答案
我在使用HTML.ValidationSummary时遇到一些问题。我不想在ValidationSummary中显示属性错误。当我设置HTML.ValidationSummary(true)时,它不会显示来自ModelState的错误消息。当字符串上的控制器操作中存在某些异常时
MembersManager.RegisterMember(member);
Catch部分向ModelState添加错误:
ModelState.AddModelError("error", ex.Message);
但ValidationSummary不显示此错误消息。当我设置HTML.ValidationSummary(false)时,所有消息都会显示,但我不想显示属性错误。如何解决此问题?
下面是我正在使用的代码:
型号:
public class Member
{
[Required(ErrorMessage = "*")]
[DisplayName("Login:")]
public string Login { get; set; }
[Required(ErrorMessage = "*")]
[DataType(DataType.Password)]
[DisplayName("Password:")]
public string Password { get; set; }
[Required(ErrorMessage = "*")]
[DataType(DataType.Password)]
[DisplayName("Confirm Password:")]
public string ConfirmPassword { get; set; }
}
控制器:
[HttpPost]
public ActionResult Register(Member member)
{
try
{
if (!ModelState.IsValid)
return View();
MembersManager.RegisterMember(member);
}
catch (Exception ex)
{
ModelState.AddModelError("error", ex.Message);
return View(member);
}
}
查看:
<% using (Html.BeginForm("Register", "Members", FormMethod.Post,
new { enctype = "multipart/form-data" })) {%>
<p>
<%= Html.LabelFor(model => model.Login)%>
<%= Html.TextBoxFor(model => model.Login)%>
<%= Html.ValidationMessageFor(model => model.Login)%>
</p>
<p>
<%= Html.LabelFor(model => model.Password)%>
<%= Html.PasswordFor(model => model.Password)%>
<%= Html.ValidationMessageFor(model => model.Password)%>
</p>
<p>
<%= Html.LabelFor(model => model.ConfirmPassword)%>
<%= Html.PasswordFor(model => model.ConfirmPassword)%>
<%= Html.ValidationMessageFor(model => model.ConfirmPassword)%>
</p>
<div>
<input type="submit" value="Create" />
</div>
<%= Html.ValidationSummary(true)%>
<% } %>