All about Programming and Sourcecode

How to add a Controller in ASP.NET MVC Application ?

Controller is one of the main component in the MVC Architecture. When the user enters the URL , the requests are first handled by the controllers which then identifies the right view to be rendered.

The controllers class is inherited from System.Web.Mvc.Controller class and it contains various action methods.

How to add a Controller in ASP.NET MVC Application ?

To add the controller in ASP.NET MVC Application , follow the below steps

1. Right click on the Controllers folder in the solution explorer and select Add menu and click “Controller” as shown in the below screenshot.

How to add a Controller in ASP.NET MVC Application ?

How to add a Controller in ASP.NET MVC Application ?

2. In the Add Controller Dialog , enter the name of the controller . For example , name the controller as “EmployeeController” . Make sure that the convention is followed where the controller name ends with Controller.

How to add a Controller in ASP.NET MVC Application ?

How to add a Controller in ASP.NET MVC Application ?

3. The Add Controller section also includes other sections like Scaffolding options which enables the developers to create the controller using templates as well as specify Model class , Data context class . Views etc and click OK.

You should see a new class file with the name “EmployeeController.cs” being created and contains the code similar to one shown below.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

namespace MvcApplication1.Controllers

{

public class EmployeeController : Controller

{

//

// GET: /Employee/

public ActionResult Index()

{

return View();

}

}

}

In this above example , the Index action returns a View which is not yet created . We will modify this action method to return a string . The modified Controller will long similar to the one shown below

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

namespace MvcApplication1.Controllers

{

public class EmployeeController : Controller

{

//

// GET: /Employee/

public string Index()

{

return "Welcome to AbundantCode.com";

}

}

}

Run the Project and enter the URL http://localhost:<port>/Employee , you will see the welcome message from the action method.

How to add a Controller in ASP.NET MVC Application ?

How to add a Controller in ASP.NET MVC Application ?

0saves
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.
 
Comments

No comments yet.

Leave a Reply