ASP.NET MVC Controller, Action Method and ActionResult

In this article I am going to explain about ASP.NET MVC Controller, its Action Method and Action Result. And how to create and use controller in MVC application.

The controller class is inherited from ControllerBase. Controller class is responsible for handling incoming request, process user input and execute requested action method, handle error, provide WebFormViewEngine to render response.


To use controller in MVC application follow below steps.


Controller Demo Application

Open your visual studio and create new Empty ASP.NET MVC application. Name it as ControllerDemo.

From Solution Explorer, right click on Controllers folder. Select Add -> Controller.

From Add Controller window, give name to controller name as CustomerController. Use Empty MVC Controller as template and click on Add.

ASP.NET MVC Add New Controller


CustomerController.cs file will get created under Controllers folder. You will see below code in CustomerController.


namespace ControllerDemo.Controllers
{
    public class CustomerController : Controller
    {
        //
        // GET: /Customer/
        public ActionResult Index()
        {
            return View();
        }
    }
}
    
            

Now if you execute the application, you will get exception Server Error in '/' Application. As it tries to execute http://localhost/home/index mentioned as defualt in Route.config file under App_Start folder and Index Action method returns a View object which is not present. You can get more info on ASP.NET MVC Routing with example.


ASP.NET MVC Action Method

ASP.NET MVC Action Methods are responsible to execute request and generate response to it. By default it generates response in form of ActionResult.

When user enters some url in browser, ASP.NET MVC architecture uses mapped routes created in Route.config or Global.asax file to determine path of action method to be executed.

Below are some example of execution of Action Method

URL: http://yourdomain.com
It executes Action method specified in Route.config file as default Action Method and default controller. You may check RegisterRoutes method from Route.config file

URL: http://yourdomain.com/customer
It executes default Action method specified of Customer controller. The default action method is sepcified in mapping of routes.

URL: http://yourdomain.com/customer/getallcustomer
It executes GetAllCustomer action method from Customer controller.

URL: http://yourdomain.com/customer/getcustomer/1
It executes GetCustomer action method from Customer controller. It also provides the CustomerID as parameter to action method.

Now you will create your new Action method of Customer controller. This action method returns All Customers.

Add below code in Customer controller which you created in previous step

.

public string GetAllCustomers()
{
    return @"<ul>
                <li>Maria Anders</li>
                <li>Thomas Hardy</li>
                <li>Victoria Ashworth</li>
                <li>Yang Wang</li>
            </ul>";
}
    
            

Now execute your application and browse to http://localhost:2246/customer/getallcustomers. You will see below screen.

ASP.NET MVC Action Method


ASP.NET MVC ActionResult

ActionResult is an abstract class defined in System.Web.MVC namespace. Most of the action methods return a object of class which is derived from ActionResult class. It represents the result of MVC action method.

In MVC most of the action method returns a View which is an instance of ViewResult class. Below code shows an example of returning a View ActionResult as a response of action method.


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

You can create your custom ActionResult return type by creating a class by deriving ActionResul abstract class.

Below are different types of ActionResult provided by ASP.NET MVC framework.


Action Result

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

Redirects to another action method by using its URL.

RedirectToRouteResult

RedirectToAction
    OR
RedirectToRoute

Redirects 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.

HttpStatusCodeResult

(None)

Returns a specific HTTP response code and description.

HttpUnauthorizedResult

(None)

Returns the result of an unauthorized HTTP request.

HttpNotFoundResult

HttpNotFound

Indicates the requested resource was not found.

FileResult

File

Returns binary output to write to the response.

FileContentResult

Controller.File(Byte[], String) or Controller.File(Byte[], String, String)

Sends the contents of a binary file to the response.

FilePathResult

Controller.File(String, String) or Controller.File(String, String, String)

Sends the contents of a file to the response.

FileStreamResult

Controller.File(Stream, String) or Controller.File(Stream, String, String)

Sends binary content to the response through a stream.

EmptyResult

(None)

Represents a return value that is used if the action method must return a null result (void).

Download source code

Speak your mind :
Leave a comment for this article on dotnetbloogers.com
User profile picture on dotnetmentors.com

by milind at 7/8/2015 12:03:00 AM
Please add some detail blogs about PartialViewResult, RedirectResult, RedirectToRouteResult ContentResult
post comment on dotnetmentors.com
User profile picture on dotnetmentors.com

by Laxmikant at 10/28/2015 2:54:00 AM
@Milind, blogs has been added for PartialViewResult and JSON Result check http://dotnetmentors.com/mvc/how-to-use-partial-view-in-mvc-with-example.aspx
post comment on dotnetmentors.com
User profile picture on dotnetmentors.com

by KEV at 7/10/2016 11:33:00 PM
Please tell me how can i call data from the table through stored procedure in DAL Class
post comment on dotnetmentors.com