Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC: Render Html.ValidationSummary only if there are errors

Tags:

asp.net-mvc

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();
    }
like image 983
Egor Pavlikhin Avatar asked Oct 07 '09 12:10

Egor Pavlikhin


2 Answers

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.

like image 123
spender Avatar answered Oct 07 '22 00:10

spender


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.

like image 26
tvanfosson Avatar answered Oct 07 '22 01:10

tvanfosson