Click here to Skip to main content
15,885,546 members
Articles / Programming Languages / C#

Controllers and Actions in ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.58/5 (14 votes)
20 May 2013CPOL5 min read 128.1K   21   3
Controllers and Actions in ASP.NET MVC.

Introduction

When you request an MVC application through the browser, a Controller is responsible for returning a response to that request.Controller may have exposes one or more Actions and return different types of action results to a Browser. For example a controller action return View,file, redirect to another controller action etc.

To create a Controller is to right click the Controllers folder in the solution explorer window in VS studio, select the "Add" menu option then select the controller.

Image 1

It display the Add Controller dialog, where you have to provide the controller name.Here one point you have to remember that controller name should follow the specific naming convention i.e.

<AnyName>+<Controller> so Controller is in the suffix.Otherwise it will not work or invoke the controller.

Image 2

Controller is a Class that inherits from the base class System.Web.Mvc.Controller. Any public method exposed by a controller is exposed as a controller action.If you want to prevent a public controller method from being invoked, you put the "NonAction" attribute over the method name.By default Index() action is the default action that is invoked on a controller on when no explicit action is mentioned.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace ControllerApplication.Controllers
{
    public class TestingController : Controller
    {
        //
        // GET: /Testing/

        
        public ActionResult Index()
        {
            return View();
        }
 
    }
}

Image 3

Multiple actions in the controller

Let us consider an example

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace ControllerApplication.Controllers
{
    public class TestingController : Controller
    {
        //
        // GET: /Testing/

        
        public ActionResult Index()   //Default Action
        {
            return View();
        }
 
        public ActionResult Testing1()   
        {
            return View();
        }
 
        public ActionResult Testing2(string x)
        {
            return View();
        }
    }
}

Here in the above code there are three actions(Index,Testing1,Testing2) are defined in the controller class "TestingController" .So to invoke the different actions you have to type into a address bar is

Pattern: {controller}/{action}/{id}

  • / TestingController/Index :- Invokes the Index() action.
  • /TestingController/Testing1 :- Invokes the Testing1() action.
  • /TestingController/Testing2/pijush :- Invokes the Testing2() action with the value "pijush" for Id parameter. 
  • /TestingController :- Invokes the Index() action

For modifying the URL pattern for invoking actions, you can modify the default route i.e. you have to create your own custom routes.

Action Results Listing

  • View():- It represents an ASP.NET MVC view i.e. when you return HTML to the browser and it is the most common ActionResult returned by a Controller.
  • PartialView():- A fragment of an ASP.NET MVC view.
  • RedirectToAction():- Redirect from one controller action to a second controller action. Possible parameters that you can use with the RedirectToAction() methods are
    • actionName: The name of a controller action.
    • controllerName: Name of a Controller.
    • routeValues: The values passed to the action.
    • E.g.:

      C#
      return RedirectToAction("Index",Testing);
      return RedirectToAction("Testing2", new {id="pijush"});

      The RedirectToAction() method returns a 302 found HTTP status code to the browser to perform the redirect to the new action.One advantage of performing a browser redirect is that it updates the browser address bar with the new URL. The disadvantage is that a browser must do a second request.

  • Redirect():- Redirection to another controller action or URL.
  • Content():- Raw content sent to the browser. There are multiple overloads of the Content() method. All the parameters are mentioned below that you can pass as an argument
    • string: The string to render to the browser.
    • contentype: The MIME type of the content (defaults to text/html).
    • contentEncoding: The text encoding of the content (e.g.:-Unicode or ASCII)
  • Json():- JavaScript object Notation (JSON) was invented by Douglas Crockford as a lightweight alternative to XML appropriate for sending data across the internet in Ajax application. E.g :- You can convert a set of database records into a JSON representation and pass the data from the server to the browser. The Json() method uses a class in the .NET framework called the JavaScriptSerializer to serialize an object into a JSON representation.
C#
public ActionResult List()
{
    var val = new List<string>
             {
                 "AAA",
                 "BBB",
                 "CCC"
             };
             return Json(val);
} 

JSON representation :- ["AAA","BBB","CCC"]  

Json() method has several overloads and supports the following parameters are

  • data: The content to serialize.
  • contentType: The MIME type of the content (default to application/json).
  • contentEncoding: The text encoding of the content(e.g. Unicode or ASCII).
  • File():- Return a file from an action. E.g.: image file, word file etc.This method accepts the following parameters which are mentioned here: filename, contentType, fileDownloadName, fileContents [instead of providing the path to the file to download, you can provide the actual file contents as a byte array], fileStream.
  • JavaScript():- Represents a JavaScript file.

Image 4

AcceptVerbs

The AcceptsVerbs attribute enables you to prevent an action from being invoked unless a particular HTTP operation is performed. E.g:- To prevent an action being invoked unless HTTP GET operation is performed.

Other HTTP operations

  • OPTIONS :- Returns information about the communication options available.
  • GET
  • HEAD :- Same as GET without returning the message body.
  • POST
  • PUT :-Same as POST
  • DELETE
  • TRACE :- Performs a message loop back.
  • CONNECT:-SSL tunneling.

ActionName

The ActionName attribute help you to expose an action with a different name than its method name.You can use this attribute in two different situation

  1. In case of Overloaded methods, you can use the ActionName attribute to expose two methods with the same name as actions with different names.
  2. Different names of the method in the controller and want to expose these methods as actions with the same name.

ActionMethodSelector

Building a custom attributes that can be apply to controller actions to control when the actions are invoked.For creating the custom attribute you have to derive the abstract class "ActionMethodSelectorAttribute". It has a single method "IsValidForRequest()" that you have to implement in your class and its return type is bool.

Unknown Actions

HandleUnknownAction():- It is called automatically when a controller cannot find an action. By default this method throws a 404 resource Not Found HTTP exception.But you can override this method in your controller class with your own custom logic or error message that you want to show.

C#
protected override void HandleUnknownAction(string actionName)
{
 ViewData["name"] = actionName;
 View("Errorpage").ExecuteResult(this.ControllerContext);
} 

References

  • Various Internet site
  • MSDN

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 4 Pin
Ujjval Shukla11-Sep-15 19:14
Ujjval Shukla11-Sep-15 19:14 
GeneralMy vote of 3 Pin
Mani Raj S7-Jan-15 9:07
Mani Raj S7-Jan-15 9:07 
GeneralMy vote of 5 Pin
Mita Joardar2-Jul-13 6:07
Mita Joardar2-Jul-13 6:07 
Nice!

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.