views:

1751

answers:

1

I have some problem with Html.ValidationSummary. I don't want to display property errors in ValidationSummary. And when I set Html.ValidationSummary(true) it does not display error messages from ModelState. When there is some Exception in controller action on string

MembersManager.RegisterMember(member);

catch section adds an error to the ModelState:

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

But ValidationSummary does not display this error message. When I set Html.ValidationSummary(false) all messages are displaying, but I don't want to display property errors. 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)%>
<% } %>
+12  A: 

I believe the way the ValidationSummary flag works is it will only display ModelErrors for string.empty as the key. Otherwise it is assumed it is a property error. There is no validation that the string you provide is/isn't a property on the Model.

ModelState.AddModelError(string.Empty, ex.Message);
Jab
Thank you. You are right, this solution works.
msi
Thanks. This was driving me nuts!
Aros