Quicktostudy
Contact Us| About Us| Terms| Privacy Policies
Dot Net MVC Tutorial

MVC Controller

MVC Controller

The MVC Controller handles all incoming URL request. Controller is a class, This is derived from the base class System.Web.Mvc.Controller. MVC controller class contains public methods called Action methods. Controller and its action method handles incoming browser requests, retrieves necessary model data and returns appropriate responses.

All MVC controller class name must end with a word "Controller". For example, controller for home page must be HomeController and controller for admin must be AdminController. All MVC controller class must be located in Controller folder of MVC folder structure.

Writing First MVC Controller

In this section, you will create a controller to handle URLs.

Creating the New MVC Controller

To create the controller, Right click the Controllers folder within the Solution Explorer and select the Add -> Controller menu item, as shown below.

MVC Controller

Select the MVC 5 Controller - Empty scaffolding template, as shown below.

MVC Controller

Name the controller StoreController and press the Add button, as shown below

MVC Controller

Writing Action Methods

StoreController already has an Index method. We will use this Index method and we will also add two additional methods to implement the two other Browse and Details. These methods (Index, Browse, and Details) within controller are called controller actions.

To get an idea of how a controller action works, follow these steps:
Step 1 Change the signature of the Index method to return a string (rather than an ActionResult) and change the return value to "Hello from Store.Index()" as follows:

  // GET: /Store/
  public string Index()
  {
  	return "Hello from Store.Index()";
  }
  

Step 2Add a Store.Browse action that returns "Hello from Store.Browse()" and a Store.Details action that returns "Hello from Store.Details()", as shown in the complete code for the StoreController that follows:

  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Web;
  using System.Web.Mvc;
  namespace MvcMusicStore.Controllers
  {
  	public class StoreController : Controller
  	{
  		// GET: /Store/
  		public string Index()
  		{
  			return "Hello from Store.Index()";
  		}
  		// GET: /Store/Browse
  		public string Browse()
  		{
  			return "Hello from Store.Browse()";
  		}
  		// GET: /Store/Details
  		public string Details()
  		{
  			return "Hello from Store.Details()";
  		}
  	}
  }
  

Step 3Run the project again and browse the following URLs:

  • /Store
  • /Store/Browse
  • /Store/Details

Accessing these URLs invokes the action methods within controller and returns string responses, as shown below.

MVC Controller
Contact Us| About Us| Terms| Privacy Policies
Powered by Lorquins Technologies© 2017 QuickToStudy.com. All Rights Reserved