Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if my model is valid from inside the razor view?

I need to do a check if my model is valid from inside my Razor view. If it's valid then I want to be able to show some HTML.

How can I do this. I want something like

@if ( Model.IsValid ) {  } 

but the above does not work

like image 298
Samantha J T Star Avatar asked Dec 22 '11 05:12

Samantha J T Star


People also ask

How do you use a model in Razor view?

Right-click in the Store Index action method and select Add View as before, select Genre as the Model class, and press the Add button. This tells the Razor view engine that it will be working with a model object that can hold several Genre objects.

How do I know my state model in view?

The ModelState can be accessed in View using the ViewData object in ASP.Net MVC Razor. 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.

What does ModelState IsValid validate?

ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process.


1 Answers

You can check whether or not the ModelState is valid, but keep in mind that you're only checking the validity of the ModelState at the time the web request was made:

@if (ViewData.ModelState.IsValid) {     ... } 

Additionally, you can check validatity of a property on the model in the view:

@if (ViewData.ModelState.IsValidField("FIELD_NAME")) {     ... } 
like image 200
Phil Klein Avatar answered Sep 20 '22 08:09

Phil Klein