ASP.NET MVC Html.ValidationSummary(true) does not display model errors

問題:

I have some problem with Html.ValidationSummary. 我有一些Html.ValidationSummary的問題。 I don't want to display property errors in ValidationSummary. 我不想在ValidationSummary中顯示屬性錯誤。 And when I set Html.ValidationSummary(true) it does not display error messages from ModelState. 當我設置Html.ValidationSummary(true)時,它不會顯示來自ModelState的錯誤消息。 When there is some Exception in controller action on string 在字符串的控制器操作中有一些異常時

MembersManager.RegisterMember(member);

catch section adds an error to the ModelState: catch部分向ModelState添加錯誤:

ModelState.AddModelError("error", ex.Message);

But ValidationSummary does not display this error message. 但ValidationSummary不顯示此錯誤消息。 When I set Html.ValidationSummary(false) all messages are displaying, but I don't want to display property errors. 當我設置Html.ValidationSummary(false)時,所有消息都顯示,但我不想顯示屬性錯誤。 How can I fix this problem? 我該如何解決這個問題?

Here is the code I'm using: 這是我正在使用的代碼:

Model: 模型:

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

Controller: 控制器:

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

View: 視圖:

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

解決方案:

參考一: https://en.stackoom.com/question/Bp99
參考二: https://stackoom.com/question/Bp99
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章