Objective

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

Part 1 of this series of tutorial could be found here

http://www.c-sharpcorner.com/UploadFile/dhananjaycoder/MVCFrameWorkPart103262009001714AM/MVCFrameWorkPart1.aspx

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.

Explaning with example

When runing a MVC dafult website , the browser request get maped in below manner. Like below in address bar of browser address is


Url in browser is http://localhost:1589/Home/About

So mapping would be like below

Home -> Conroller class

About -> Action ( Method inside HomeController class)

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

 

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();

}

}

}

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 retutn type also like string or intger. But if it is not ActionResult, return data will get convrted into string and then get render.

    ActionResult

    These are the results returend 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 Represnts HTML and markup
EmptyResult Represnts 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

http://www.c-sharpcorner.com/UploadFile/dhananjaycoder/SilverLightwithMVCFramework04032009052312AM/SilverLightwithMVCFramework.aspx

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.
  1. Redirect – Returns a RedirectResult action result.
  1. RedirectToAction – Returns a RedirectToRouteResult action result.
  1. RedirectToRoute – Returns a RedirectToRouteResult action result.
  1. Json – Returns a JsonResult action result.
  1. JavaScriptResult – Returns a JavaScriptResult.
  1. Content – Returns a ContentResult action result.
  1. 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 File->New->Project->Web->ASP.Net MVC web application.


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.


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


How to create a Controller ?


 

 

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.


Step 2

Remove Default to any signifiacnt name. here name is UST.

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



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 sollution expolere inside Controller folder.


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 colud get added later. This could be access on 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

using System.Web.Mvc;

if it is not added

Step 4

Inherit this class from Controller.

public
class
csharpController : Controller

Upto this step Controller is ready to add Actions.

Now this controller could be access as

http://localhost:1876/csharp

How to create a Action inside a Controller?

An action could get added in a controller by simply adding a public method inside controller class.

Whereas action having 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.

Haappy Coding

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s