Friday, October 14, 2011

ASP.NET MVC Overview

 The above diagram shows the relationship between the MVC Framework and the .NET Framework. Observe that the Web Forms and MVC are both built on top of ASP.NET Framework.

                     

Introduction

ASP.NET MVC is one of the methods of developing ASP.NET applications. In this article, we will go through the overview of ASP.NET MVC by creating a simple application.
ASP.NET MVC Framework is Microsoft’s Web Application development framework, the other one being traditional webforms framework.
MVC or Model View Controller is a design pattern that addresses the separation of concerns(Soc) which is the process of identifying and separating the application into distinct parts like UI, Logic and Data Access.
Soc has proven to be useful in the design of web applications. Keeping the view separate from the other parts of the application means that we can easily change the view without affecting the rest of the application.
Similarly, if we want to change the main application logic, we just need to change the controller.
ASP.NET MVC is an implementation of the MVC design pattern. The framework helps Test Driven Development which is a method of development in which Unit Test Cases are written before the rest of the application.
While building web applications, developers can either choose the web forms model or the MVC model depending on the requirements of the application.
An MVC application consists of Model, View and Controller at its core:
  1. Model: Consists of the data access logic and the classes that represent the objects in the application domain (Business Objects)
  2. View: A view contains HTML markup
  3. Controller: Consists of the main application flow logic
Let’s start with creating simple MVC application to understand the basics of the MVC application. We will start by creating a blank ASP.NET MVC application.
Once the web application is created, we will add the functionality to make it work.




Adding the Controller

For adding the controller, we will right click the controllers folder and select Add -> Controller. We will type the name NamesController in controller name dialog.
Note that the Controller name must end with Suffix Controller. Doing so creates a controller with the default code. We have renamed the action as in the following code.



//public class ProductsController : Controller
    //{
    //    //
    //    // GET: /Names/

    //    public ActionResult Electronics()
    //    {
    //        ViewData["Message"] = "Electronics Products Listing";
    //        return View();
    //    }
    //}
Here NamesController is the name of our Controller. It inherits from System.Web.Mvc.Controller Framework class. View is a method defined in the base controller class.
Controller is just a normal class that contains action methods which is a non static public method defined in the Controller class.
A controller action is invoked in response to the requested URL like Products.
We will see later how URLs map to the Actions defined in the controller class.
A controller action always returns an action result which determines the response returned to the browser. In the above code, the action returns viewresult which represents an ASP.NET view.
Few of the actionresults are:
  • ViewResult - Represents the HTML for the view
  • RedirectResult - Represents Redirect to another controller action
  • ContentResult - Represents RAW URL sent to the browser
  • EmptyResult - Represents that no result is returned by the action
Typically, we call the method defined in the base controller class whose return type is the appropriate view instead of directly returning the action result.
To invoke the above action, we just need to type the following in the browser Names/Index.
If we want to add another action to the controller, we just need to add another public method to the controller. We can also specify the name of the view explicitly as:
return View("index");
 
The above code will return the index view instead of returning the default view (which in this case is also index). Now that we have our controller in place, let us create our first view.
View: Views are responsible for rendering the Interface on the browser. To create a view in the controller, we right click on the action and select Add View.



We will leave the default options selected in the create new view dialog. This creates a new view with two content elements. In the first content, we place the content we want to appear in the title, while in the second content we place the content we want to appear in the body of an HTML page. We will replace the second content control with the following:
 <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2> <%=ViewData["Message"]  %></h2>
</asp:Content> 
Remember that we have assigned the ViewData property in the Controller’s Index action method. View data is a dictionary object used to pass the information between the controller and the view. Here, we are using the view data property to display the message in the view.

Routing

In traditional web applications, the URL is hardwired with the application code that gets executed or resource that is requested. URL Routing decouples the URL with the application code.
URL ----------> ROUTING ----------> APPLICATION LOGIC
One of the advantages of this decoupling is that it makes the URL more user friendly since we can give more meaningful names to the URL. For example, instead of using something like ListProduct.aspx, we can use simply Products which is more meaningful to the end user.
Routing defines a URL pattern that should match to access the application.
We normally define the routes in the global.asax file since it contains the application life cycle events. By default, routes are defined in the RegisterRoutes method which is called from Application_Start event.
  routes.MapRoute(
  "Default",
                 "{controller}/{action}/{id}",
                 new { controller = "Products", action = "Electronics",
  id = UrlParameter.Optional }
            );
The second parameter in the MapRoute method matches all the URLs that satisfy the above pattern e.g. {Controller}/{Action}/{id} and the appropriate Controllers action method is called for the matched URL.

No comments:

Twitter Bird Gadget