Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating posted form data in the ASP.NET MVC framework

I've been playing around with the ASP.NET MVC Framework and the one thing that's really confusing me is how I'm meant to do server side validation of posted form data. I presume I don't post back to the same URL, but if I don't, how do I redisplay the form with the entered data and error messages? Also, where should the validation logic go? In the model or the controller? This seems to be one of the few areas where web forms are much stronger (I miss the validation controls).

like image 970
Ben Mills Avatar asked Aug 13 '08 19:08

Ben Mills


People also ask

What is form validation in MVC?

Validation is an important aspect in ASP.NET MVC applications. It is used to check whether the user input is valid. ASP.NET MVC provides a set of validation that is easy-to-use and at the same time, it is also a powerful way to check for errors and, if necessary, display messages to the user.

Where is data validation in MVC?

You validation should be in Model section of MVC. As models have various fields, only models can know what combination of inputs make that model valid.

Which property of controller is used for validating form in server side in MVC?

IsValid property. If input data is not valid then ModelState. IsValid will return false and shown error as shown below. When all the validation will be passed then ModelState.


1 Answers

Here's an overview of the flow in MVC:

  1. /new - render your "New" view containing a form for the user to fill out
    • User fills out form and it is posted to /create
    • The post is routed to the Create action on your controller
    • In your action method, update the model with the data that was posted.
    • Your Model should validate itself.
    • Your Controller should read if the model is valid.
    • If the Model is valid, save it to your db. Redirect to /show to render the show View for your object.
    • If the Model is invalid, save the form values and error messages in the TempData, and redirect to the New action again. Fill your form fields with the data from TempData and show the error message(s).

The validation frameworks will help you along in this process. Also, I think the ASP.NET MVC team is planning a validation framework for the next preview.

like image 153
Lance Fisher Avatar answered Sep 30 '22 11:09

Lance Fisher