We pay for user submitted tutorials and articles that we publish. Anyone can send in a contributionLearn More
So far we have looked at the requirements for our fictional application and the data structure that goes with that, the application’s Model using a repository pattern , and URL Routing to provide friendlier URLs.
What we have covered so far really is just supporting code. In this post we’ll look the first of two parts that really hold our application together, the Controller. In the next post we’ll cover the View and how it ties into the Controller.
Controllers are the glue that hold the MVC pattern together. Every request made to our application will get mapped to a Controller. This Controller will handle any work we need to do like gathering data from the Model and rendering Views. For example if our application receives a request of http://yourdomain.com/Task/Show/2 ASP.Net MVC would map the request to, using the default mapping, a controller called TaskController. That Controller might look like this:
As you can see, a Controller is just a class that inherits from the Controller base class. The inheritance brings some very handy features that we’ll look at as this post progresses.
Controller Actions are methods of your controller class that get called based on the request your application receives. For example, using the controller we defined above, if our application received a request like http://yourdomain.com/Task/Show/45 then the Show() method of our TaskController would get called because Show is the action portion of our application’s route table. You can read more about URL Routing in the previous post. From a security stand point it is important to know that just about any method of a controller that is public can potentially get called just by providing the correct action name in the URL. It isn’t hard to imagine how this could get abused by someone with less than honorable intention. It is important to only expose controller methods if they actions that you intend your application to use. Everything else should be kept private. Controller actions cannot be overloaded and they cannot be made static.
That pretty much wraps up this post. You should have a good understanding of Controllers and Actions now and how to use them in your applications. In the next post will wrap up this series by looking at the View which is the final piece of the MVC puzzle. To make sure you don’t miss a beat grab the Dev102 RSS feed. You may also be interested to follow what I have to say on my web development blog or grab my RSS feed.
Tags :ActionResultAJAXASP.NET MVCContentResultController
Copyright © 2012 Dev102.com
Breeze : Designed by Amit Raz and Nitzan Kupererd