Channels ▼
RSS

Tools

5 Reasons For Taking a Closer Look at ASP.NET MVC


Dan Wahlin (Microsoft Most Valuable Professional for ASP.NET and XML Web Services) is the founder of The Wahlin Group (www.TheWahlinGroup.com) which provides .NET, SharePoint, and Silverlight consulting and training services. Dan also founded the XML for ASP.NET Developers Web site (www.XMLforASP.NET), which focuses on using XML, ADO.NET and Web Services in Microsoft’s .NET platform Dan has co-authored/authored several books on .NET, including Professional Silverlight 2 for ASP.NET Developers, ASP.NET 2.0 MVP Hacks, Professional ASP.NET AJAX, XML for ASP.NET Developers. Dan blogs at http://weblogs.asp.net/dwahlin.


I've been an ASP.NET Web Forms fan since ASP.NET was first released. Still, I keep an open mind when it comes to new technologies and I decided to experiment with the new ASP.NET MVC framework that Microsoft recently released so I would be able to use it with consulting projects and for training my company provides. I was so impressed with some of the things I could do that I'm already using it on a customer project and thought I'd share some of the things I really like about the framework.

Before moving on, I know what some of you are already thinking because I thought the same things: "I don't need all that testing stuff promoted by MVC people!"or "That's an overly complex framework for ‘letter of the law' developers!"or "I can't use all my familiar ASP.NET server controls!"or "I don't care about absolute control over the HTML that's output!". I can tell you that while I do believe in unit testing and use it in my ASP.NET Web Forms consulting projects (see my previous post on the subject), I'm far from a letter-of-the-law type developer (opinionated for sure….but not annoyingly opinionated :-)) and don't really need absolute control over HTML output in many cases. However, there are several other reasons why I think you should look at ASP.NET MVC and see if it can benefit your projects at all.

In this article I outline five things I really like about ASP.NET MVC. However, I don't address separation of concerns, unit testing, complete control over HTML, and the like. If you want those things you get them too, so please keep that in mind before yelling, "You didn't mention testing!". It's up to you to create test projects or not, and ASP.NET MVC provides a very testable framework if you want to leverage it. Having said that, let's get started with a few terms before jumping into the details:

  • Model. Represents data used in the application that's ultimately retrieved and manipulated using business rule and data access classes (you could/should have these classes in ASP.NET Web Forms as well)
  • View. Handles presenting data to the end user (Similar to an .aspx page in ASP.NET Web Forms)
  • Controller. Retrieves data from the Model and passes it to a View (somewhat analogous to a code-behind page in ASP.NET Web Forms…but quite a bit different in functionality)

Reason #1: Automatic Mapping of Control Values to Object Properties

I don't enjoy writing tedious code and am always coming up with ways to minimize and refactor where possible. One of the nicest features in the ASP.NET MVC framework is the built-in ability to automatically map control values to objects. With ASP.NET Web Forms you find yourself doing the following quite often (although some controls when used with the <%# Bind %> expression can do some mapping too):


protected void btnSubmit_Click(object sender, EventArgs e)
{
    Person p = new Person();
    p.FirstName = FirstName.Text;
    p.LastName = LastName.Text;
    UpdatePerson(p);
}

This is a simple example that can quickly become complex depending upon the number of controls in your forms. ASP.NET MVC uses specialized objects called "Controllers" to serve up pages (called "Views") and within a controller class you can write methods (called "Actions"). Actions can capture the form data submitted by an end user and automatically map it to custom object properties without you having to write any mapping code as shown above. For example, consider the following ASP.NET MVC controls defined with a View named EditCustomerProfile (only a portion of the view is shown for brevity). To prove I'm not a letter-of-the-law person, you'll see I went with a table here (yeah I know, divs would work too, but I'm not in a div mood today):


<table width="640" cellspacing="5">
    <tr>
        <td style="width:30%"><label for="Customer.FirstName">First Name:</label></td>
        <td style="width:70%">
            <%= Html.TextBox("Customer.FirstName", Model.Customer.FirstName)%>
            <%= Html.ValidationMessage("FirstName", "*")%>
        </td>
    </tr>
    <tr>
        <td><label for="Customer.LastName">Last Name:</label></td>
        <td>
            <%= Html.TextBox("Customer.LastName", Model.Customer.LastName) %>
            <%= Html.ValidationMessage("LastName", "*")%>
        </td>
    </tr>
    <tr>
        <td><label for="Customer.Company">Company:</label></td>
        <td>
            <%= Html.TextBox("Customer.Company", Model.Customer.Company)%>
            <%= Html.ValidationMessage("Company", "*")%>
        </td>
    </tr>
    <tr>
        <td><label for="Customer.Phone">Phone:</label></td>
        <td>
            <%= Html.TextBox("Customer.Phone", Model.Customer.Phone)%>
            <%= Html.ValidationMessage("Phone", "*")%>
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="submit" value="Update Profile" />                  
            <span class="StatusMessage" style='color:<%= Model.StatusColor %>'><%=Model.StatusMessage %></span>
        </td>
    </tr>
</table>

The first thing to notice is that controls are defined differently in ASP.NET MVC than in ASP.NET Web Forms. That's a topic for a later article. The "classic ASP"style <% tags gave me heartache at first but having built many Views now I actually like the simple syntax for defining controls (no more runat="server"!).

Take a look at the ID for each control and notice that they all have "Customer" prefixing the name (Customer.FirstName, Customer.LastName, Customer.Company, etc.). This is all the mapping code you need. The method (Action) that handles the posted data simply needs to define a type that has properties that map with the form fields and the mapping happens "automagically". You can even customize the mapping if desired or perform mapping using built-in controller methods such as UpdateModel().

Here's what the EditCustomerProfile() method (Action) looks like that handles the posted data. You can see that it accepts a Customer parameter named customer that will automatically receive the posted control values and update the appropriate values. The parameter name is key here since that's what makes the auto-mapping possible (recall that each control was prefixed with "Customer"; ase doesn't matter here). There's a lot more that could be said about this particular topic, but this should give you an idea of how the auto-mapping works. A nice discussion of the different mapping options available in ASP.NET MVC (referred to as "ModelBinders") can be found here. Potential issues that you should know about with regard to auto-mapping are also covered here.


[Authorize]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditCustomerProfile(Customer customer)
{
    try
    {
        if (customer.IsCustomerValid)
        {
            OperationStatus opStatus =_CustomerRepository.Update(customer);
            if (opStatus.Status)
            {
                ViewData["Status"] = "true";
                return View("EditCustomerForm", 
                    new CustomerViewModel(customer,"Navy","Your profile information was saved."));
            }
        }
    }
    catch 
    {   
      //Log             
    }
    ViewData["Status"] = "false";
    ModelState.AddModelErrors(customer.GetRuleViolations());
    return View("EditCustomerForm", new CustomerViewModel(customer, "Red", "There was a problem updating your profile."));
}

Reason #2: Automatic Generation of Views

Again, Views display the data given to them by Controllers. If you have a strongly-typed object (such as Customer above) that you will be passing to a View, Visual Studio can automatically generate the View for you and even add the controls that map to the respective object properties that will be bound as well as validation controls (although you'll have to write the code to actually do the validation). When creating Views using the IDE you can use the following Add View window:

This saves time when defining controls. It also save times in mapping control IDs to object properties. If you don't like the default code that's output you can change the templates or add new custom templates. They're located at C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC\CodeTemplates by default. For example, if you prefer tables for your forms you could tweak one of the template files such as Edit.tt like this:


        <fieldset>
            <legend>Fields</legend>
               <table style='width:100%;'>
<#
    foreach(KeyValuePair<string, string> property in properties) {
#>        
                    <tr>
                        <td style='width:30%'>
                            <label for='<#= property.Key #>"><#= property.Key #>:</label>
                        </td>
                        <td style='width:70%'>
                            <%= Html.TextBox('<#= property.Key #>", <#= property.Value #>) %>
                            <%= Html.ValidationMessage("<#= property.Key #>", "*") %>
                        </td>
                    </tr>
<#
    }
#>
                
                    <tr>
                        <td colspan="2">
                            <input type="submit" value="Save" />
                        </td>
                    </tr>
                </table>
        </fieldset>

    <% } %>

    <div>
        <%=Html.ActionLink("Back to List", "Index") %>
    </div>

Reason #3: UpdatePanel-Like AJAX Support -- But on a Serious Diet

If you use AJAX in your applications and are fond of the UpdatePanel control in ASP.NET Web Forms (some like it…some hate it) you may be aware that it can transmit a lot of data during an asynchronous postback (ViewState, ControlState, etc.) if you're not careful. ASP.NET MVC has built-in AJAX support as well and is just as easy to use. You can create forms that perform partial-page updates and you don't even have to work hard to do it. Here's an example of using the AjaxHelper to do the equivalent of an UpdatePanel:


<% using (Ajax.BeginForm("EditCreditProfile", new AjaxOptions { UpdateTargetId = "CreditForm", OnSuccess = "onEditOfficeProfileSuccess" }))
   {
%>
    <div id="CreditForm">
        <% Html.RenderPartial("EditCreditForm",Model.CreditProfileViewModel); %>
    </div>
<% } %>

The Ajax.BeginForm() call says that when the form is submitted (the form controls are defined in an EditCreditForm View User Control) a Controller Action named EditCreditProfile should be called asynchronously. When the call returns the div with an id of CreditForm will be updated automatically with the resulting data. This sends significantly smaller payloads as compared to the UpdatePanel which is nice when you need that type of functionality.

Built-in support for adding AJAX functionality to links is also available in ASP.NET MVC through the AjaxHelper. Check out the ActionLink() method if you're interested in hooking a link to an Action using AJAX techniques.

Reason #4: Integration with Other JavaScript Libraries such as jQuery

I mentioned earlier that I don't always care about having complete control over the exact HTML that is output as long as it's valid. However, I do care about the ID of the controls that are output because with ASP.NET Web Forms IDs are auto-generated depending upon the container control that they live in (ASP.NET 4.0 will give you more control over IDs though). While there are certainly workarounds for this, it can be a bit painful at times especially working with controls nested in a GridView or User Control. ASP.NET MVC gives you 100% control over the IDs that are output so using script libraries such as Prototype or jQuery are that much easier. And, like ASP.NET Web Forms, you get jQuery intellisense if the proper documented script files are available.

Here's a simple example of handling the AjaxHelperobject's OnSuccess event to load and process JSON data using jQuery:


function onEditOfficeProfileSuccess()
{
    GetOfficeProfiles();
}
function GetOfficeProfiles()
{
    CallService('/Account/GetOfficeProfiles', { customerID: $('#CustomerID').val() }, GetOfficeProfilesComplete);
}
function GetOfficeProfilesComplete(json)
{
    var s = $().parseTemplate($('#OfficeProfilesTemplate').html(), json);
    $('#OfficeProfilesOutput').html(s);
}
function CallService(url, data, callback)
{
    $.ajax({
        url: url,
        cache: false,
        dataType: "json",
        data: data,
        success: callback
    });
}

Reason #5: Promotes Better Coding Practices and a Solid Application Architecture

I admit that this final reason isn't as sexy as the others, but it's definitely a benefit especially to larger enterprises with a lot of applications to build and maintain. ASP.NET MVC helps guide developers down the path of designing architecturally sound applications from the start. Now, don't get me wrong, you can build solid applications using Web Forms as well and I've built many that had Presentation, Business, Data and Model layers. However, a lot of developers (at least based on what I hear in some of the training classes we run) still put a lot of code in the code-behind file of a Web Form. That works, but isn't very re-useable and definitely isn't very testable. ASP.NET MVC guides developers to build architecturally sound applications that separate presentation, business and data logic so that it's more reusable (and testable). That doesn't mean that the code is good as every developer has different skills of course, but it helps when people start things off on the right foot. If you've tried both frameworks (WebForms and MVC) I'd love to hear your thoughts on this final reason.

Summary

Microsoft is going to support both ASP.NET Web Forms and ASP.NET MVC so you can go with either framework and be fine down the road (until some new technology is invented of course). Having had a chance to use both frameworks I can tell you that each has its own set of pros and cons. Hopefully, this article has given you a few reasons to research the ASP.NET MVC framework and take a closer look at what it offers. I'll still be using Web Forms on some projects but it'll be harder for me to choose between the two frameworks now. I really like the control that ASP.NET MVC gives you.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video