Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialCory Watson
3,269 PointsImplementing Serverside Validation Using Modelstate
I'm currently building a website and am looking to implement some of these validation rules when submitting a form. I know that I can write the validation directly for each page I'm creating within it's corresponding ActionResult method, but I would much rather write the validation code once as it's own method within the controller and call the method within each ActionResult (for example, my ActionResult Create, ActionResult Edit, ActionResult Review) in the controller. I want to do this to keep the code more simple and readable, especially because the validation code that I'm writing is about 500 lines long. Also, I'd rather not use the model for validation, just the controller if possible. How can I do this?
1 Answer
Pieter Bracke
4,078 PointsWhy don't you make a seperate class like "Validation.cs" then in that class create a method where your validation rules live. Then make an instance of that class in your Controller's constructor and use the instance of that class to call on your method in your different Action results?
I do have to say it is recommended to use model state because this ensures strong Data. Also if you have 500 lines of validation I would recommend splitting those in to different methods in the "Validation.cs" class and only calling the ones you need for the different Action Results...
So to summarize try to use loosely coupled services (the class which holds the rules doesn't interfere with your controller class) and Strong typed DataModels
Hope this helps a bit