While explaining routing in MVC 4, I have explained that Controller is responsible for returning a response based on the request. Also the first call will always go to controller in MVC. The base class of the controller is ControllerBase, which will provide all the MVC handling. Controller is responsible for the following:
- Responsible to call appropriate action method and validate it can be called.
- Process the logic.
- Error handling.
- Providing the default WebFormViewEngine class for rendering ASP.NET page types (views).
Let us see how to add a new controller in MVC 4:
Note: All controller classes must be named using the "Controller" suffix.
Now just look at the following code which got generated after adding a new “HomeController”.
- namespace MvcApplication1.Controllers
- {
- public class HomeController: Controller
- {
-
-
-
- public ActionResult Index()
- {
- return View();
- }
-
- }
- }
Actions Methods:
Under the controller we use to write the “Action Methods," which are bound with the logic to process the request and will generate the response accordingly. Based on the routing configuration defined in “Global.asax” file,
Now let see how actions methods work based on Route:
It executes Action method specified in Route.config file as default Action Method and default controller.
- https://www.yoursite.com/Employee
It executes default Action method specified in Employee controller.
- https://www.yoursite.com/Employee/GetDetails
It executesGetDetails Action method specified in Employee controller.
- https://www.yoursite.com/Employee/GetDetails/720501
It executes GetDetails Action method specified in Employee controller. And also it will provide the employee id to that method and based on this we can get the details from DB.
ASP.NET MVC ActionResult:
There are various types of action results available in MVC 4. When a new controller gets created one or more action result will come by default. In MVC most of the action method returns a View which is an instance of ViewResult class.
ActionResult | Helper Method | Description |
ViewResult | View | Renders a view as a web page |
PartialViewResult | PartialView | Renders a partial view, which defines a section of a view that can be rendered inside another view. |
RedirectResult | Redirect | Redirect to another action method |
RedirectToRouteResult | RedirectToRoute | Redirect to another action method |
ContentResult | Content | Returns a user-defined content type |
JsonResult | Json | Returns a serialized JSON object |
JavaScriptResult | JavaScript | Returns a script that can be executed on the client |
FileResult | File | Returns a binary output to write to the response |
EmptyResult | (None) | Returns a null result
|