Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only show a div if the modelstate has errors

I have a div which contains a generic styling and error message if a user enters the wrong username/password combo.

I only want to display this div if the user has entered the wrong information. Is there something on my View I could do, something like:

@if(ModelState.HasErrors)
{
      <div>This login failed</div>
}
like image 683
CallumVass Avatar asked Feb 21 '12 10:02

CallumVass


People also ask

How do I display ModelState errors?

Display Custom Error Messages Above, we added a custom error message using the ModelState. AddModelError() method. The ValidationSummary() method will automatically display all the error messages added into the ModelState .

Which property is used to determine an error in ModelState?

Errors property and the ModelState. IsValid property. They're used for the second function of ModelState : to store the errors found in the submitted values.

What is ModelState clear ()?

Clear() is required to display back your model object. Posted on: April 19, 2012. If you are getting your Model from a form and you want to manipulate the data that came from the client form and write it back to a view, you need to call ModelState. Clear() to clean the ModelState values.

What is the purpose of ModelState IsValid property?

ModelState. IsValid property can be used to perform some logical operations based on the values submitted by the User. Note: If you want to learn about Client Side validations in ASP.Net MVC Razor, please refer ASP.Net MVC: Client Side validations using Data Annotation attributes and jQuery.


1 Answers

@if (!ViewData.ModelState.IsValid)
{
      <div>This login failed</div>
}

Side note, can't you use the built-in Validation helpers?

Controller:

if (yourError)
{
   ModelState.AddModelError("Error", "This login failed");
   return View();
}

View:

@Html.ValidationMessage("Error")
like image 122
RPM1984 Avatar answered Sep 19 '22 14:09

RPM1984