Controller in ASP.Net MVC Framework


Objective:

Purpose of this tutorial to explain all about Controller in ASP.Net MVC Framework.

Part 1 of this series of tutorial could be found here

ASP.Net MVC controller

  1. MVC controller takes user request in browser.
  2. These are responsible for responding to request made against ASP.Net MVC web site.
  3. Browser request is mapped to a Controller.

Explaining with example

When running a MVC default website, the browser request get mapped in below manner. Like below in address bar of browser address is

1.gif
Url in browser is

http://localhost:1589/Home/About

So mapping would be like below

Home -> Controller class
About -> Action ( Method inside HomeController class)

So on seeing , HomeController class , there is a method called About.
2.gif

Action

  1. These are the public method inside a Controller class. Through these methods user interacts to ASP.Net MVC web site. These methods are exposed to outside world.
  2. Any Action could be invoked from outside just by typing its address in address bar of browser.
  3. Action return type must be ActionResult. It might have any other return type also like string or integer. But if it is not ActionResult, return data will get converted into string and then get render.

ActionResult

These are the results returned by the Actions. Action result is result which controller returns in response of browser request.

These are types of action result supported by MVC Controller.

All types of action result is inherited from ActionResult base class.

Action result Purpose
ViewResult Represents HTML and markup
EmptyResult Represents NO Result
RedirectResult Represents a redirection to a new URL
JsonResult Represents a JavaScript Object Notation result that can be used in an AJAX application or may be in SilverLight application

See my article here.
JavaScriptResult Represents a JavaScript script
ContentResult Represents a text result
FileContentResult Represents a downloadable file (with the binary content).
FilePathResult Represents a downloadable file (with a path).
FileStreamResut Represents a downloadable file (with a file stream).

Note: action result are not get called directly. Instead of them method of controller base class get called.
List of methods of Controller base class is as follows
  1. View - Returns a ViewResult action result.
  2. Redirect - Returns a RedirectResult action result.
  3. RedirectToAction - Returns a RedirectToRouteResult action result.
  4. RedirectToRoute - Returns a RedirectToRouteResult action result.
  5. Json - Returns a JsonResult action result.
  6. JavaScriptResult - Returns a JavaScriptResult.
  7. Content - Returns a ContentResult action result.
  8. File - Returns a FileContentResult, FilePathResult, or FileStreamResult depending on the parameters passed to the method.

Example of returning a JSON action result
Step 1:
Create a new MVC web application. Select Filearrow.gifNewarrow.gifProjectarrow.gifWebASP.Net MVC web application.

3.gif

Step 2:

Open HomeController class and add the below code there

 

public ActionResult List()
{
    List<int> r = new List<int>();
    for (int i = 0; i < 100; i++)
    {
        r.Add(i);
    }
    return Json(r);

}


So now Home Controller class will look like ( HomeController class is in Controller folder)

HomeController.cs

 

using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewData["Message"] = "Welcome to ASP.NET MVC!";
            return View();
        } 

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

        public ActionResult List()
        {
            List<int> r = new List<int>();
            for (int i = 0; i < 100; i++)
            {
                r.Add(i);
            }
            return Json(r);
        }
    }

}


Step 3
:

Run the application by pressing F5. Home page of MVC will get open. Type below URL in the address bar of browser

http://localhost:1549/Home/List

Note : port number will be different, when you run it on different system. For my system it is 1549.

The below dialog box will pop up.

4.gif


Save this somewhere and try to open that file in NOTEPAD or something like that. All number from 0 to 99 will be there.

5.gif

How to create a Controller?

6.gif

Method 1:

By right clicking on Controller folder and selecting Add then New Controller

Step 1:

Right click on Controller folder and add then Controller.

 7.gif

Step 2:

Remove Default to any significant name. Here name is UST.

Note: Each Controller class must append with keyword Controller. So make sure there is no space while renaming default to other name.

 8.gif

If check box is checked the by default framework will create stub for Create and Update and Details. Here it is unchecked.

Now USTController should be listed in solution explorer inside Controller folder.

 9.gif

Step 3:

By default below class will get created

HomeController.cs

 

using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.Mvc;
using
System.Web.Mvc.Ajax; 

namespace MvcApplication1.Controllers
{
    public class USTController : Controller
    {
        //
        // GET: /UST/
        public ActionResult Index()
        {
            return View();
        }
    }
}


Here Action could get added later.

This can be accessed in browser as

http://localhost:1987/UST

Method 2:

Creating a manual class inside Controller folder and derive this class from Controller base class.

Step 1:

Right click on Controller and add new class by clicking on add.

Step 2:

Give name but make sure, it is appended with Controller. For example if desired name of controller is csharp then here name will be csharpController. So name of the class will be csharpController.cs

Step 3:

Add namespace System.Web.Mvc if it is not added

Step 4:

Inherit this class from Controller.

 

public class csharpController : Controller


Up to this step Controller is ready to add Actions.

Now this controller could be accessed as

http://localhost:1876/csharp

How to create a Action inside a Controller?

An action can be added in a controller by simply adding a public method inside controller class.

Whereas action will have the following restrictions

  • The method must be public.

  • The method cannot be a static method.

  • The method cannot be an extension method.

  • The method cannot be a constructor, getter, or setter.

  • The method cannot have open generic types.

  • The method is not a method of the controller base class.

  • The method cannot contain ref or out parameters.

In Part 3 Model will get covered.

Till then Happy Coding

Up Next
    Ebook Download
    View all
    Learn
    View all