Anatomy of an ASP.Net MVC Application

21 בדצמבר 2008

תגיות: ,
3 תגובות

Anatomy of an ASP.Net MVC Application

Anatomy ASP.Net MVC Application In order to fully understand how this magic of ASP.Net MVC works, I went to build an MVC application from scratch.

1. Create a new ASP.Net Web Application. This creates an application with a Default.aspx page, a standard web.config file, and adds the initial references to the project.

2. Add references to System.Web.Abstractions.dll, System.Web.Routing.dll and System.Web.Mvc.dll, all of them can be found at c:\Program Files\Microsoft ASP.NET\ASP.NET MVC Beta\Assemblies folder.

Use the MvcHttpHandler to handle MVC requests. Open the code-behind file of Default.aspx (default.aspx.cs) and in the Page_Load method, process the request in MVC style:

protected void Page_Load(object sender, EventArgs e)
{
  HttpContext.Current.RewritePath(Request.ApplicationPath);
  IHttpHandler httpHandler = new MvcHttpHandler();
  httpHandler.ProcessRequest(HttpContext.Current);
}

3. Add a Global Application Class (global.asax), and in the Application_Start method, map the route to the home controller.

protected void Application_Start(object sender, EventArgs e)
{
  RouteTable.Routes.MapRoute("Default Route",
    "{controller}/{action}",
    new { controller = "Default", action="Index" });
}

4. In order to use the MapRoute and IgnoreRoute methods, you should add a using directive to use the namespace System.Web.Mvc, since those are extension methods. The MapRoute method takes a name of a route as the first parameter, a URI template as the second, and default values as the third. Notice that the default values object should have properties that correspond the names of the properties in the URI template. The route above maps an incoming Url to a combination of a controller and an action.

Anatomy ASP.Net MVC Application5. Create a default controller. Add a class to the web application under a Controllers folder and name it DefaultController. Notice the naming convention for it: Default comes from the route default value and the controller is just a suffix in the convention.

This class should inherit from System.Web.Mvc.Controller class, and should contain a public method with a name the corresponds to an action. Since the default action is Index (taken from the default route), then the class should look like this:

public class DefaultController : Controller
{
  public string Index() 
  {
    return "Hello, world";
  }
}

6. Run the application, and navigate to the application directory ( “/” ), what you should get is the response “hello, world”.

 Anatomy ASP.Net MVC Application

But, If you try to navigate to the Index action in the Default controller (/Default/Index), you will get an error.

7. Add the Url Routing Module. Open the web.config, and locate the <httpModules> tab in the system.web section. There, register the Url Routing Module:

<httpModules>
  ...  
<
add name="UrlRoutingModule"
       type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, 
Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35
" />
</httpModules>

8. Run the application and navigate to the Index action in the Default Controller. Now, you should get the same response as earlier.

Anatomy ASP.Net MVC Application

9. Return a view as the result of the Index action. Change the return value of the Index method in the default controller to be of type ActionResult. There are several types of results we can return (such as JosnResult, ContentResult etc.) but in this sample we will return a ViewResult, by calling the View method.

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

Anatomy ASP.Net MVC Application Create a view that corresponds to this action. When called parameterless, the View method will look for a view whose name is equals to the name of the action, inside a folder the corresponds to the name of the controller. Create a new ASP.Net Form called Index.aspx inside Views\Default\ folder.

In order to make this an MVC View, open the code behind file (Index.aspx.cs) and change the class to inherit from System.Web.Mvc.ViewPage.

Edit the page (in design mode or source mode) and add a greeting message:

<body>
  <form id="form1" runat="server">
    <div>
      <h1>Hello, world</h1>
    </div>
  </form>
</body>

10. Run the application and you should receive the response from the View we’ve just created. The routing engine called the Index action in the Default controller, which returned the Index.aspx view.

11. Display data in the View. Open the controller, and in the Index method, add data to the ViewData dictionary:

public ActionResult Index()
{
  ViewData["name"] = "Guy";
  return View();
}

Now, in the view markup, use that data in the greeting line:

<body>
  <form id="form1" runat="server">
    <div>
      <h1>Hello, <%= ViewData["name"] %></h1>
    </div>
  </form>
</body>

12. Run the application and receive a greeting message bounded to the data that the controller has added to the dictionary.

Anatomy ASP.Net MVC Application

In this post I build an ASP.Net MVC application from scratch in order to understand the anatomy of an ASP.Net MVC application and the magic behind this framework. This understanding can help me with adding MVC capabilities to my existing web applications as well.

Enjoy!

הוסף תגובה
facebook linkedin twitter email

3 תגובות

  1. Florian15 בפברואר 2009 ב 10:45

    Great post, saved me hours of work! Many thanks.

  2. Jim19 בפברואר 2009 ב 17:40

    A minor tweak – ditch the server form in your view… it doesn't make sense with mvc.

  3. bhavin patel2 במרץ 2009 ב 19:03

    plz explain anatomy of asp .net

Comments are closed.