Reader Level:
ARTICLE

Implementation and Use of ASP.NET MVC

Posted by Ashish Shukla Articles | ASP.NET MVC May 14, 2012
In this article we will see the use and basic implementation of ASP.NET MVC.
  • 0
  • 0
  • 5108

In this article we will see the use and basic implementation of ASP.NET MVC.

To better understand why we will ever need to use ASP.NET MVC instead of the traditional, user friendly ASP.NET WebForm's to develop ASP.NET applications we need to look into some of its shortcomings and how they are addressed in ASP.NET MVC applications.

ViewState Load

ViewState maintains the state across postbacks; it requires that the data be transferred back and forth between the client and the server. The data that is transferred can become so large that it consumes a heavy bandwidth, thus creating poor response for the user.

Mix of Presentation and Application Logic

Code behind frequently modifies the Web Form controls and also includes the application logic. This approach of mixing the presentation and application logic together results in code that is difficult to maintain.

Limited HTML control

Since the server controls render themselves, this could often be different from the HTML we want generated, like the client id created for the server controls (though this shortcoming has been fixed in version 4.0) and the automatically generated JavaScript.

Hiding of the true nature of the web creates problems

As we know, HTTP is a stateless protocol. Webforms hide this fact by creating an abstraction for us. Thus Web Forms are an abstraction and are meant to be used as such so that developing a web application has the same experience as developing a Windows application.

Now let us see how ASP.NET MVC addresses these shortcomings

There is no ViewState Load

ASP.NET MVC generated pages do not contain any view state data so the size of such pages is much less than the same pages generated using the ASP.NET WebForm approach.

Does not Hides the true nature of the web

MVC does not hide the true nature of the web as a stateless protocol but still it provides a way to write code that is easier to maintain and that is free of complications.

Encourages to have More Control over the HTML

WebForms, while trying to abstract the fact that HTTP is a stateless protocol, does a lot of things hidden for us, like generating the JavaScript and CSS. If we create similar pages in ASP.NET MVC and WebForms and see the HTML source for the generated pages we will see that the ASP.NET MVC page does not change the control ids and there is no JavaScript and CSS generated while the similar WebForm page automatically generates a lot of JavaScript and CSS which we might not be aware of.

MVC architecture can be depicted by the following diagram

MVC1.jpg

In the MVC architecture incoming requests are handled by the controller which works with the model, selects the view and prepares the View data which is rendered by the selected view.

In short MVC is separating three main responsibilities into three main layers.

  1. Business Logic -> Model
  2. Presentation Logic -> View
  3. Application Logic -> Controller

Please note that Application logic and Presentation logic are most of the times mixed together in the WebForm's in the event handlers.

Creating an MVC application in Visual Studio

Let us understand some of the concepts in an ASP.NET MVC application first.

Controller: In MVC incoming requests are handled by the controllers. A Controller is a class inheriting from the built-in Controller class which implements the IController interface.

Action: Each public method in the controller is an action that can be invoked using a URL.

View: Accepts the data in the ViewData objects passed to it by the Controller and renders them.

Model: Objects that are passed between controller and view.

Routing System: maps the URL's to controllers and actions (To decouple the URLs from the web pages and also makes the URL search engine freindly).

While creating an ASP.NET MVC application in Visual Studio we have two choices of templates to choose from.

ASP.NET MVC 2 Web Application template

This creates a sample application preconfigured with things like authenctication, styles and navigation.

ASP.NET MVC 2 Empty Web Application template

Create only the files and folders required by every ASP.NET MVC application.

MVC2.jpg

Visual Studio provides us various templates for creating web applications.

Here we will be creating a controller using the ASP.NET MVC 2 application template.

Adding the Controller

Now we replace the code in the HomeController in the Controllers folder with the following code:

[HandleError]
    public class HomeController : Controller
    {
        public string Index()
        {
            return "MVC is great!";
        }
    }

Now when we run the application we will see "MVC is great!" rendered in the browser window. We didn't create a view or action but still the correct output is displayed because under the default routing system configuration the application root (that is, the root of the virtual directory) is mapped to the Index action on the HomeController.

So when we launch the application the Index() action is automatically invoked.

Adding the View

The above code correctly displays the intended output but mostly we will use views to render the HTML. We need to return a ViewResult type from the action method to use the view to render the HTML.

Replace the above code with the following:

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

Conventionally, views use the same name as the actions. Now we need to generate the default view for the above action method. To do so right-click on the Action and select "Add View" in the context menu.

MVC3.jpg

Doing so generates an Index.aspx view which we can find in the views folder.

Now we will replace the content in the Index.aspx view with our content "MVC is great!".

Running the application renders the same message as the previous one but this time makes use of the view.

The responsibility of the Controller is to generate some data which is rendered by the view so we need some mechanism to pass that data from the controller to the view. To do so we use the data structure called ViewData.

Replace the above code in the HomeController with the following code:

public ViewResult Index()
{
      ViewData["MVC"] = "MVC is great!";
       return View();
}

And replace the content we previously added in the Index.aspx view with the following:

<%: ViewData["MVC"]%>

So now instead of hardcoding the content in the view we are passing it from the controller.

This was a brief overview of ASP.NET MVC to get us started.
 

COMMENT USING

Trending up