|
Resources » .NET programming » ASP.NET/Web Applications
Introduction to ASP.NET MVC
This article gives you an introduction to the ASP.NET MVC framework. Are you looking for ASP.NET Model-View-Controller framework? Then, here you go for it.
|
Introduction MVC stands for Model-View-Controller and is one of the most popular design patterns for decoupling data access and business logic from data presentation and user interaction. The ASP.NET MVC Framework addresses aspects of programming that are extremely important for developers and their productivity such as code reusability, testing, and separation of presentation and business logic concerns.
An MVC Application is designed and implemented using the following three attributes

- Model: The model contains the core information for an application. This includes the data and validation rules as well as data access and aggregation logic.
- View: The view encapsulates the presentation of the application, and in ASP.NET this is typically the HTML markup.
- Controller: The controller contains the control-flow logic. It interacts with the Model and Views to control the flow of information and execution of the application.
This separation of entity allows you to have nimbleness and flexibility in building and maintaining your application. For example, by separating the views, you can iterate on the appearance of your application without touching on any of the core business logic. You can also separate work by role, so that, for example designers can work on the views, while developers work on the model.
ASP.NET MVC brings the power of this development paradigm to ASP.NET development, allowing you to use your .NET development skills to build MVC applications. It gives you
- Complete control over your HTML Markup
- Enables rich AJAX and jQuery integration
- Allows you to create SEO-friendly URLs for your site
- Makes Test Driven Development (TDD) easy
Motivating MVC
Most applications, and especially Web applications, have their presentation layer mixed up with some business logic and data access code. As an example, think of a classic ASP.NET page. You define the user interface by composing and configuring server controls until you obtain the desired markup. Next, you use a code-behind class to add some handlers for the various events fired by controls and provide any required glue code. In such pages, more often than not, data access code is interspersed with presentation logic. Such ASP.NET pages whose code-behind classes contain a mixture of presentation, business and data access code, are quite difficult to maintain. And they are definitely challenging to test appropriately.
User interface facilities (i.e., wizards and tools in Visual Studio) tend to encourage developers to put in the presentation layer more than it should. The presentation layer acts as a catch-all for logic that reasonably belongs to other layers. At the end of the day, you can still have the application working and perform well. Behind the scene, though, you get a too high level of coupling and subsequently high costs of maintenance. What if, in fact, at some point you need to add a new feature or re-implement an existing one? Not having a well designed structure of classes and lacking a clean separation of presentation, business and data layers, most that you can do is cutting and pasting code and run pages over and over again to test results against expectations.
The classic code-behind model of ASP.NET provides the tools for building great and well-designed applications, but it leaves most of it up to the individual developer or team. As a result, too many applications out there work well, but are not well designed. Over the years, this fact raised the need of a radically different approach to Web programming. The MVC pattern was soon identified as an excellent approach to Web development. MVC ensures a clean separation between the data model and the user interface in such a way that changes to the user interface doesn't affect data handling. At the same time, the data model and related access code can be refactored without the need of changing the user interface accordingly.
Comparing the MVC Framework to Classic ASP.NET
The ASP.NET MVC Framework is essentially the Microsoft's attempt to create an ASP.NET programming environment centered on the MVC pattern. For the time being, the MVC Framework should be considered an alternative to Web Forms. To some extent, the MVC Framework and Web Forms have in common more or less what cars and motorcycles share. Both can take you somewhere else, but with different speed, comfort, sense of freedom, size of the trunk.
The MVC Framework doesn't support classic postbacks and viewstate and doesn't consider any URL as the endpoint to a physical server file to parse and compile to a class. In ASP.NET, you have a 1:1 correspondence between a URL and a resource.
In the MVC Framework, a URL is seen as the mean to address a logical server resource, but not necessarily an ASPX file to parse. So the URLs employed by the pages of an MVC Framework application have a custom format that the application itself mandates. In the end, the MVC Framework employs a centralized HTTP handler that recognizes an application-specific syntax for links. In addition, each addressable resource exposes a well-known set of operations and a uniform interface for executing operations.
A URL Does Not Equal a Page
When you build a traditional ASP.NET Web Forms application or an Active Server Pages application, there is a one-to-one correspondence between a URL and a page. If you request a page named SomePage.aspx from the server, then there had better be a page on disk named SomePage.aspx. If the SomePage.aspx file does not exist, you get an ugly 404 – Page Not Found error.
When building an ASP.NET MVC application, in contrast, there is no correspondence between the URL that you type into your browser's address bar and the files that you find in your application. In an ASP.NET MVC application, a URL corresponds to a controller action instead of a page on disk.
In a traditional ASP.NET or ASP application, browser requests are mapped to pages. In an ASP.NET MVC application, in contrast, browser requests are mapped to controller actions. An ASP.NET Web Forms application is content-centric. An ASP.NET
MVC application, in contrast, is application logic centric.
Representational State Transfer (REST)
Have you ever heard about Representational State Transfer, or REST for short? Well, REST is an architectural pattern that defines how network resources should be defined and addressed in order to gain shorter response times, clear separation of concerns between the front-end and back-end of a networked system. REST is based on three following principles:
- An application expresses its state and implements its functionality by acting on logical resources.
- Each resource is addressed using a specific URL syntax.
- All addressable resources feature a contracted set of operations
As you can see, the MVC Framework fulfills it entirely. So here's an alternate way of looking at the MVC Framework. It is an ASP.NET framework that performs data exchange by using a REST model versus the postback model of classic ASP.NET. Each page is split into two distinct components -controller and view - that operate over the same model of data. This is opposed to the classic code-behind model where no barrier is set that forces you to think in terms of separation of concerns and controllers and views. However, by keeping the code-behind class as thin as possible, and designing the business layer appropriately, a good developer could achieve separation of concerns even without adopting MVC and its overhead. MVC, however, is a model superior to a properly-done code-behind for its inherent support for test-driven development (TDD).
The figure below summarizes classic ASP.NET and the MVC Framework.

REST is a possible alternative to the postback model, whereas MVC is an alternative to code-behind.
Code Behind v/s Controllers
ASP.NET MVC's version of the code-behind file is the controller class. The controller class works differently however; with ASP.NET MVC, there aren't any server-side controls, page lifecycle, and some of those other familiar page components that web forms developers are used to. Take a look at a sample code-behind page,
Sample ASP.NET Web Forms Page
public class CustomerPage : Page { protected withevents TextBox FirstName; protected withevents TextBox LastName; protected withevents GridView OrdersGrid; protected override void OnLoad(EventArgs e) { UserInformation info = (UserInformation)Session["User"]; this.FirstName.Text = info.FirstName; this.LastName.Text = info.LastName; var dal = new OrdersDAL(); this.OrdersGrid.DataSource = dal.GetOrders(info.ID); this.OrdersGrid.DataBind(); }
protected void OrdersGrid_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.ItemType == DataRowControlState.DataItem) { e.Row.Cells[3].Text = Order)e.Row.DataItem).HasShipped ? "Yes" : "No"; } } }
Here we have a page that pulls the first and last name from a session variable that stores a UserInformation object across page requests. Next, the code-behind invokes a method in the data access layer to get orders for a specific user by its ID, and binds them to the grid. So, in this simple example, the code-behind file is responsible for assigning values to the individual controls in the page, for loading data into a grid, and for communicating with the data access layer. With MVC, we see the alternative controller approach.
Sample ASP.NET MVC Controller
public class CustomerModel { public UserInformation User { get; set; } public IEnumerable<Order> Orders { get; set; } }
public class CustomerController : Controller { public ActionResult Index() { var dal = new OrdersDAL(); var user = (UserInformation)Session["User"]; return View(new CustomerModel { User = user, Orders = dal.GetOrders(user.ID) }); } }
There are some quite substantial changes between this MVC controller and the previous ASP.NET web form. First, the CustomerModel class contains the actual data that gets displayed in the view. In the web form, the code-behind file assigns the data to the view; in MVC, this responsibility will be shown later. Additionally, the controller creates this model for the view, as well as does the data access dirty work, and accessing the data from the session. So how do we work with textboxes and grids and those other controls we have been so used to working with? Below is a sample
MVC view that displays the UI.
Sample View
<@Page .. > <html> <body> <% Html.BeginForm(); %> <div> <span>First</span> <%= Html.TextBox("FirstName", Model.User.FirstName) %> </div> <div> <span>Last</span> <%= Html.TextBox("LastName", Model.User.LastName) %> </div> <div> <table> <thead> <tr> <th>Date</th> <th>Amount</th> <th># Products</th> <th>Has Shipped?</th> </tr> </thead> <tbody> <% foreach (var order in Model.Orders) { %> <tr> <td><%= order.Date %></td> <td><%= order.Amount.ToString("C") %></td> <td><%= order.ProductCount %></td> <td><%= order.HasShipped ? "Yes" : "No" %></td> </tr> <% } %> </tbody> </table> </div> <% Html.EndForm(); %> </body> </html>
There are quite the changes than web forms developers are used to. The MVC view takes over more of the ownership of displaying the data within the UI. It does look similarly to the way web forms works, with the addition of the view specifying the data to load, and the view taking over how the UI will appear without the involvement of a code-behind file.
Resources
In ASP.NET web forms, developers used a wide array of external resources to store data with. Users could leverage mechanisms like Session, Cache, Application, and other collections for storing data across page postbacks. ASP.NET MVC still uses these to retain its data, but this has gotten better.
LifeCycle
With ASP.NET web forms, the page fires an Init, Load, PreRender, and Unload events (to name a few). ASP.NET MVC, however, doesn't leverage this lifecycle; instead, it runs requests to action methods (usually one, but other action methods can run additionally through some helper methods).
Attachments
|
Read related articles: ASP.NET MVC MVC architecture MVC Difference between classic ASP.Net and MVC
Did you like this resource? Share it with your friends and show your love!
|
|
|
| Author: Siti 03 May 2010 | Member Level: Gold Points : 0 | Hey Nishikant, its a nice article, thanks for sharing it.
| | Author: Manigandan 03 May 2010 | Member Level: Gold Points : 0 | Hi Nishikant,
Good and Useful Article.
Thanks for Posting.
| | Author: Nishikant 03 May 2010 | Member Level: Gold Points : 0 | Thank you siti and Manigandan.
| | Author: manisha 05 May 2010 | Member Level: Gold Points : 0 | good article and thanx for sharing with us.
-- Manisha Chaubey
| | Author: Bablu 05 May 2010 | Member Level: Bronze Points : 1 | Is it something like n-tier architecture ? Any difference between MVC and 3-tier or n-tier architecture ?
| | Author: Pawan Awasthi 21 Jul 2011 | Member Level: Diamond Points : 1 | Hi,
Good article for introductory training... Great one...i am learning the mvc working..
thank alot
| | Author: Kamlesh Mohanty 01 Mar 2012 | Member Level: Gold Points : 0 | Thankyou very much for this wonderful article
| | Guest Author: viswa 23 Oct 2012 | very nice article. Thanks to share.
|
 Follow us on Twitter: https://twitter.com/dotnetspider
|
|