Dmytro
Dmytro

Reputation: 17176

How can I validate specific field/property of specific model instance in ASP .NET MVC?

I have a model class with 4 properties:

public class ModelClass
    {
        [Required]
        public string Prop1 { get; set; }

        [MaxLength(5)]
        public string Prop2 { get; set; }

        [MinLength(5)]
        public string Prop3 { get; set; }

        [MinLength(5)]
        public string Prop4 { get; set; }
    }

View, where I enter only prop2:

@model ModelClass
@Html.TextBoxFor(m => m.Prop2)    

And some controller:

[HttpPost]
        public ActionResult Index(ModelClass postedModel)
        {
            var originalModel = Session["model"] as ModelClass;
            return View();
        }

The thing is: entire model is stored in Session, because it is filled on separated views. What I need is to validate only Prop1 of the model, which was stored in Session. If validation fails I need to redirect to some other View1 if Prop1 is invlaid or View3 if Prop3 is invalid etc. In controller I have posted model with only Prop2 and model from Session. I can't use ModelState and it's methods such as ModelState.IsValidField() for example because it will be the validation info of posted model. Also I can't use controller.TryValidateModel(originalModel) because I just get false and I'll get no info about why it is false, so I will not be able to redirect to View1 if Prop1 is invalid or to View3 if Prop3 is invalid. So how can I validate only Prop1 of originalModel?

Upvotes: 0

Views: 1414

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

Use view models:

public class Step1ViewModel
{
    [Required]
    public string Prop1 { get; set; }
}

and then make your view strongly typed to the view model:

@model Step1ViewModel
@Html.TextBoxFor(m => m.Prop1) 

and finally have your HttpPost controller action take the view model as action argument so that you could successfully validate it only in the context of the current wizard step:

[HttpPost]
public ActionResult Index(Step1ViewModel postedModel)
{
    if (!ModelState.IsValid)
    {
        // validation for this step failed => redisplay the view so that the 
        // user can fix his errors
        return View(postedModel);
    }

    // validation passed => fetch the model from the session and update the corresponding
    // property
    var originalModel = Session["model"] as ModelClass;
    originalModel.Prop1 = postedModel.Prop1;

    return RedirectToAction("Step2");
}

Upvotes: 1

Related Questions