-3

I just started using MVC this week and was wondering where does input validation go?

I have 1 model: Data.cs

    public partial class Data
    {
        public Games getGames(int id)
        {
            return (from c in this.Games
                where c.game_id == id
                select c).FirstOrDefault();
        }

        public Genre getGenre(int id)
        {
            return (from c in this.Genre
                    where c.genre_id == id
                    select c).FirstOrDefault();
        }

        public Platform getPlatform(int id)
        {
            return (from c in this.Platform
                    where c.platform_id == id
                    select c).FirstOrDefault();
        }
    }

And then i have 3 controllers, one for GameController, GenreController, PlatformController.

I need input validation the create view/method for all 3 of these controllers which each have their own Create method, where do I put my validation? Is it in the views or model or controllers?

  • Sharing your research helps everyone. Tell us what you've tried and why it didn’t meet your needs. This demonstrates that you’ve taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer. Also see How to Ask – gnat Feb 10 at 20:05
0

In MVC, the Model does the validation. You shouldn't be able to construct and use an invalid Model. Controller handles invalid model errors. View displays the errors.

You CAN validate both in the view and controller. But then the model is anemic.

For complex scenarios, you should look at the builder pattern with interface segregation.

  • How would i implement validation in Data.cs for all three of my controllers? For instance PlatformController has a Genre varchar(max) field, how would i validate this in the model shown above – Cracks Feb 10 at 20:04
  • public Platform getPlatform(int id) { if(id == null) { throw new Exception("Invalid data"); } In well designed apps, Model does not equal to database model. I wrote an article about repositories, you can read it here: skatech.io/architecture/… – Štef FoReal Feb 10 at 21:18

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.