Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to ignore some properties (on a POCO) when validating a form in ASP.NET MVC3?

Tags:

i've got a sign up wizard for new user registration. When I try to goto the 2nd page, I get validation errors because my User object hasn't been fully populated, yet. Is there any way I can tell each ActionMethod to ignore some properties when it checks for the ModelState.IsValid checks?

eg. (Simplified, pseduo code)

public class User {    [Required]    public string Name; // Asked on page 1.    [Required]    public int Age; // Asked on page 1.    [Required]    public string Avatar;  // Asked on Page 2. } 

it complains saying that the Avatar is required/can't be null. But i don't get a chance to ask the user to fill this in, until the next page.

Is it possible to ask to ignore this check, in page 1?

like image 728
Pure.Krome Avatar asked Mar 06 '11 07:03

Pure.Krome


People also ask

Which of the following property is used to validate model?

IsValid property is checked and if the Model is valid, then the value if the ViewBag object is displayed using Razor syntax in ASP.Net MVC.

Which of the following property can stop client-side validation check?

To disable client-side validation, set the page's ClientTarget property to 'Downlevel' ('Uplevel' forces client-side validation). Alternatively, you can set an individual validator control's EnableClientScript property to 'false' to disable client-side validation for that specific control.

What is the purpose of ModelState IsValid property?

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.


2 Answers

You can use the Bind Attribute for this: http://ittecture.wordpress.com/2009/05/01/tip-of-the-day-199-asp-net-mvc-defining-model-binding-explicitly/

A better option would be to use ViewModels.

http://weblogs.asp.net/shijuvarghese/archive/2010/02/01/view-model-pattern-and-automapper-in-asp-net-mvc-applications.aspx

like image 126
Linkgoron Avatar answered Oct 20 '22 12:10

Linkgoron


In the action just remove the errors for the items not yet checked for. This then makes your model valid for the items already checked

foreach (var error in ModelState["Avatar"].Errors)  {       ModelState["Avatar"].Errors.Remove(error);  } 

or

ModelState["Avatar"].Errors.Clear(); 
like image 20
Darroll Avatar answered Oct 20 '22 11:10

Darroll