November 1, 2012

In Asp.Net Mvc, Controllers are classes that query or update model data, load a specific View template and handle user inputs. Controllers can be added in an Mvc project by right clicking the Controllers directory and choosing Add > Controller.

1

I have named the Controller - DemoController - note the naming convention.

2

Visual Studio generates the following code by default.

Default Controller Code
  1. namespace MvcDemo.Controllers
  2. {
  3.     public class DemoController : Controller
  4.     {
  5.         //
  6.         // GET: /Demo/
  7.  
  8.         public ActionResult Index()
  9.         {
  10.             return View();
  11.         }
  12.  
  13.     }
  14. }

I will update the Index() method to return some string.

Index Method
  1. public string Index()
  2. {
  3.     return "You are viewing Index method od DemoController";
  4. }

Note that, I have changed the return type from ActionResult to string. Then, run the page in debug mode and the url http://localhost:50376/demo produce the result shown below. As you can see, its the same string that was part of the Index method.

3

The important thing to note is the url ends with /demo which is also the Controller’s name. In Mvc, the url controls the Controller, Method and parameters passed to the application. It has the format /Controller/Method/{Parameters} . Index is the default method name and therefore not needed to be specified.

I will now add another method - Home – that will display the name and age based on parameters.

Home Method
  1. public string Home(string name, int age)
  2. {
  3.     return "Hello " + name + ". You are " + age.ToString() + " years old";
  4. }

It’s a simple method that return a string based on the parameters. When the page is run, the following is displayed.

4

Note that, MVC automatically binds the query strings to the relevant parameters in the method.

0 comments:

Reference: Shahed Kazi at AspNetify.com