Hacker News new | ask | show | jobs
by mattmanser 4620 days ago
Unfortunately you've misunderstood MVC.

None of that code belongs in the controller. Your 'typical' controller is anything but. All that code belongs in the model.

Your controllers should have zero LINQ statement. You should do all of the validation in the model and the validation failures should returned in a List.

This stuff's been in MVC for years:

http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mv...

When people talk about 'light' or 'skinny' controllers, this is what they're talking about.

So we're not doing MVC wrong, you've just developed bad habits from bad microsoft examples, work with some experienced Devs so they can teach you how to do it correctly.

2 comments

So, kindly watch the way you throw the word "you" around. I did not write the article, I just wanted to see what the community might have to say about it. I am coming to understand MVC decently well.

That said, your points are good, and I agree, based on what I have learned myself to this point.

:-)

What's the advantage?

Is the model constantly pulling session state to validate against?

Does this prevent caching of data on the models? Or is there 'supposed' to be some even higher level API manager that deals with the responses before they get to the model?

Your controller should be passing the session state to the model (passing the items needed from session state for the model to manipulate data). Models should have no concept of a session. They should be almost entirely self-contained.

Controllers should do only basic validation (length, format, etc.)

It sounds like you're stuck using `Session` object which you should almost never touch in ASP.Net MVC.

HTTP is stateless. You should program accordingly and not rely on the old ASP.Net webforms ways, they were extremely broken and taught some developers some very bad habits (view state was a terrible, terrible idea. Session state should be used in extremely rare circumstances and it's much better to never use it).

That's one of the reasons MVC caught on so fast. It actually reflects what in reality is happening and is not the terribly leaky abstraction that Webforms was.

In the controller you get an updated object from your repository on each request. You update it with the data that you received in the request (and MVC can do this for you itself). You ask it to validate itself. You save if valid. You return your success view. You don't save if not valid, you return the validation errors.

Hence the controller is only a few lines.

That's how you're supposed to program in MVC because HTTP is stateless. And because SQL is much faster than you probably think it is. And that makes the code vastly simpler. And you can cache persistent things like the data for common dropdowns in memory using the actual `System.Runtime.Caching` functionality.