9

Html.ValidationSummary() is still being rendered even if the model state is valid.

This example doesn't work:

<% if (!this.ViewData.ModelState.IsValid)
{ %>
<%= Html.ValidationSummary()%> 
<% } %>

There is still an empty 'ul' tag being rendered. How do I make it render only if the ModelState is not valid?

EDIT Turns out the ModelState is really invalid, but my code does not add any error messages, it's just invalid for no obvious reason.

[AcceptVerbs("POST")]
public ActionResult Login(string username, string password, bool? remember)
    {
        if (string.IsNullOrEmpty(username))
        {
            ModelState.AddModelError("Username", "Username is required");
        }
        if (string.IsNullOrEmpty(password))
        {
            ModelState.AddModelError("Password", "Password is required");
        }

        if (ModelState.IsValid)
        {
            ; // this point is never reached
        }

        return View();
    }

3 Answers 3

6

If the info you provide is correct, then this.ViewData.ModelState.IsValid is most definitely false. There must be other code here which you don't provide.

Sign up to request clarification or add additional context in comments.

Comments

2

The source code says that when the model state is valid, the helper returns a null string. I suspect that your model state is really invalid but that there hasn't been a message added. Or, it could be that the markup is really coming from something else on your page -- maybe even added with javascript.

Comments

2

Check ClientValidationEnabled and UnobtrusiveJavaScriptEnabled in app settings. Turning these off if they aren't in use may fix this issue.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.