Blog Archives

Requiring SSL For ASP.NET MVC Controllers

There are quite a few posts out there about switching to SSL when a user visits specific areas of a website but I figure the more the merrier so here’s yet another one.

My company is in the process of rolling out an ASP.NET MVC site for a client and specific actions and controllers need to have SSL running to ensure that no sensitive information gets out such as passwords and credit cards.  If a user visits the site using http:// I need to switch them to https:// in certain parts of the website.  Fortunately, ASP.NET MVC is quite extensible so it only took about 4-5 minutes to get a simple solution in place. 

The easiest way I know of to switch to SSL for specific controllers or actions is to create an ActionFilterAttribute that handles redirecting them to an https:// address.  Classes that derive from ActionFilterAttribute can be placed immediately above actions or even controllers in cases where the filter needs to apply to all actions in the controller.  For my situation I needed entire controllers to be SSL-enabled so I placed the attribute above the controller class name.

Here’s an example of the simple RequiresSSL attribute class:

using System;
using System.Web;
using System.Web.Mvc;

namespace Helpers
{
    public class RequiresSSL : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpRequestBase req = filterContext.HttpContext.Request;
            HttpResponseBase res = filterContext.HttpContext.Response;

            //Check if we're secure or not and if we're on the local box
            if (!req.IsSecureConnection && !req.IsLocal)
            {
                string url = req.Url.ToString().ToLower().Replace("http:", "https:");
                res.Redirect(url);
            }
            base.OnActionExecuting(filterContext);
        }
    }
}


A couple of people (thanks Jon and Phil) commented that the ToLower() call I had above could cause consequences with QueryString data.  I could take ToString() out but some people may type “HTTP” instead of “http” which would mess up the replace call.  For the current application I’m working on I only have integers being passed around on the QueryString so it didn’t affect me at all but it definitely could affect string data being passed.  The suggestion was to use the UriBuilder class and after thinking it through more I agree.  Here’s a different version of the RequiresSSL class that uses the UriBuilder class.

 

using System;
using System.Web;
using System.Web.Mvc;

namespace Helpers
{
    public class RequiresSSL : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpRequestBase req = filterContext.HttpContext.Request;
            HttpResponseBase res = filterContext.HttpContext.Response;

            //Check if we're secure or not and if we're on the local box
            if (!req.IsSecureConnection && !req.IsLocal)
            {
                var builder = new UriBuilder(req.Url)
                {
                    Scheme = Uri.UriSchemeHttps,
                    Port = 443
                };
                res.Redirect(builder.Uri.ToString());
            }
            base.OnActionExecuting(filterContext);
        }
    }
}


The RequiresSSL attribute can then be placed above the appropriate action or controller:

[HandleError]
[RequiresSSL]
public class AccountController : Controller
{
    ...
}


If you’re running IIS7 and want to get a test SSL certificate setup for testing purposes check out my good friend Rob Bagby’s excellent post on the subject.

Deploying ASP.NET Applications to Medium Trust Servers

99% of the projects my company works on for clients are deployed internally to an enterprise environment managed by a company.  We rarely have to worry about deploying to a shared hosting environment which is nice.  One of the client projects we finished up recently based on ASP.NET MVC, PLINQO and jQuery was deployed to a shared hosting provider for the client and nothing worked initially.  Everything worked locally of course even if we hit the hosting provider’s database from the staging server code base.  It’s never fun to have development or staging working with the same code failing in production.

After researching the error more we thought it related to data access permissions since we were getting null reference errors as collections were converted to lists (data wasn’t being returned from the database).  Finding the root cause of errors in this situation is like finding a needle in a haystack since you can’t attach a debugger, can’t run SQL Profiler or do anything aside from looking at log files, make code changes, FTP the files to the server and see what happens. 

After thinking through it more and running several isolated tests we realized it wasn’t a data access error that we were getting (even though that’s what logs led us to believe).  With a little research I came across the good old <trust> element that can be used in web.config.  It’s not something that I personally have had to use for over 5 years so I completely forgot about it.  By placing the following in web.config you can simulate a medium trust environment:

<system.web>
  <trust level="Medium"/></system.web> 

Changing the trust level made the staging environment fail with the same error shown on the shared host (which was awesome….rarely am I excited to get an error).  We found out that a PLINQO assembly we were using didn’t allow partially trusted calls so we located the source for that assembly, recompiled it to allow partially trusted callers and everything was fine. 

Bottom Line/Lesson Learned: If you’re deploying to a medium trust hosting environment you’d be wise to set the trust level to Medium up front to save time and energy down the road.

Video: Getting Started with ASP.NET MVC 1.0

I had the opportunity to speak at the Best of Mix 09 Phoenix event with Tim Heuer and Rob Bagby and had a lot of fun hanging out with everyone.  I was the last talk and due to time constraints didn’t get a chance to cover everything I had hoped to cover, but all of the important topics were discussed. 

The projection screen doesn’t show up too well in the video unfortunately, but all of the slides and sample code can be downloaded here for those that may be interested in following along. The talk covers the fundamentals of ASP.NET MVC, discusses some great features the framework offers and describes how jQuery and even Silverlight can be integrated.  The downloadable code samples demonstrate all of the features discussed in the video.

Getting Started with ASP.NET MVC 1.0 

Click here to view in Windows Media Player (right-click and you can save the file)

Logo

For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit www.thewahlingroup.com/.

Emulating the UpdatePanel in ASP.NET MVC 1.0 with AjaxHelper

I just finished up a client application based on ASP.NET MVC 1.0 and thought I’d blog about some of the things I really liked.  If you didn’t catch my earlier post titled 5 Reasons You Should Take a Closer Look at ASP.NET MVC and are interested in learning more about what the MVC framework offers I’d recommend reading that first.  The client application my company built required a lot of AJAX functionality behind the scenes and I used jQuery along with MVC controller actions to pass JSON data back and forth in many cases.  However, I did take the UpdatePanel type approach in a few cases since it’s quite easy to do and very efficient as far as the data that gets passed back and forth between the client and server.

ASP.NET MVC 1.0 provides an AjaxHelper class that exposes a BeginForm() method.  HTML controls wrapped in the BeginForm() area are automatically AJAX enabled much like the ASP.NET UpdatePanel.  However, because ASP.NET MVC doesn’t use ViewState or ControlState at all, the calls back to the server are much more efficient when compared to the UpdatePanel (you can use a tool such as Fiddler to verify this:  www.fiddlertool.com).  Here are the basic steps to AJAX-enable sections of a view in ASP.NET MVC.

1. Add Ajax.BeginForm into your View

<% using (Ajax.BeginForm("EditCustomerProfile", null,
   new AjaxOptions { UpdateTargetId = "CustomerForm", OnSuccess = "onEditCustomerProfileSuccess" },
   new { id = "EditCustomerProfileForm" }))
   {
%>

<% } %>


BeginForm() has 11 different overloads that can be used.  This example creates an AJAX-enabled section using the AjaxHelper’s BeingForm() method and defines that a controller action named EditCustomerProfile will be called to retrieve the data.  Any route data that needs to be passed can be specified in the second parameter.  The third parameter represents the AjaxOptions that will be used as the client and server interact.  In this case I specify that a control with an ID of CustomerForm will be updated with the data returned from the server.  I also call a JavaScript success callback named onEditCustomerProfileSuccess to perform other necessary actions in the application if the AJAX call returns successfully:

function onEditOfficeProfileSuccess(content)
{
    if ($('#OfficeProfileValSummary').length == 0) //No validation control found so OK
    {
        ClearOfficeProfileControls();
    }
    GetOfficeProfiles();
}

The final parameter represents properties that are added to the form tag generated by BeginForm().  I simply assign the id of the form tag to EditCustomerProfileForm which is done to make it easier to filter controls using jQuery selectors elsewhere in the application.

2. Add the UpdateTargetID div

Once BeginForm() is defined you need to specify the object (div, span or other object) that will receive updates from the server as AJAX calls are made.  In my case I want an end user to complete a form, submit it to the server, validate it, perform business rules there, etc. and then return the form back to the client with a status message about the action.  The form is defined in a user control which is embedded within my ASP.NET MVC view using the HtmlHelper’s RenderPartial() method.  Since the form area gets updated after the call I wrap it with a div that has an ID of CustomerForm (the UpdateTargetID shown above).  Here’s the completed code:

<% using (Ajax.BeginForm("EditCustomerProfile", null,
   new AjaxOptions { UpdateTargetId = "CustomerForm", OnSuccess = "onEditCustomerProfileSuccess" },
   new { id = "EditCustomerProfileForm" }))
   {
%>
    <div id="CustomerForm">
        <% Html.RenderPartial("EditCustomerForm",Model.CustomerViewModel); %>
    </div>
<% } %>


When user submits the form and data returns from the server the CustomerForm div will automatically be updated without having to write any JavaScript code….just like the ASP.NET Web Forms UpdatePanel. The code for the controller action named EditCustomerProfile is shown next.  If everything validates properly it returns the EditCustomerForm user control with a message letting the client know that everything worked.  If errors are found they are added into the model’s error collection and displayed in the form.

[Authorize]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditCustomerProfile(Customer customer, string email)
{
    string emailMessage = null;
    try
    {
        //#### Handle Email
        if (!String.IsNullOrEmpty(email) && Regex.IsMatch(email, @"^w+@[a-zA-Z_]+?.[a-zA-Z]{2,3}$"))
        {
            emailMessage = UpdateEmailAddress(email);
        }
        else //Email address is null or doesn't follow the RegEx pattern
        {
            emailMessage = "Please check that you entered your email address properly.";
        }

        //#### Handle updating Customer object data
        if (emailMessage == null && customer.IsCustomerValid)
        {
            OperationStatus opStatus = _CustomerRepository.Update(customer,
                c => c.CustomerID == customer.CustomerID);
            if (opStatus.Status)
            {
                ViewData["Status"] = "true";
                return View("EditCustomerForm",
                    new CustomerViewModel(_CustomerRepository.Get(c => c.CustomerID == customer.CustomerID),
                        "Navy", "Your profile information was saved."));
            }
        }
    }
    catch (Exception exp)
    {
        Logger.Log("Error in AccountController.EditCustomerProfile", exp);
    }
    ViewData["Status"] = "false";
    List<RuleViolation> violations = customer.GetRuleViolations().ToList();
    if (emailMessage != null) violations.Add(new RuleViolation("Email", emailMessage));
    ModelState.AddModelErrors(violations);
    return View("EditCustomerForm", new CustomerViewModel(_CustomerRepository.Get(c => c.CustomerID == customer.CustomerID),
        "Red", "There was a problem updating your profile."));
}

Adding UpdatePanel-like functionality into ASP.NET MVC applications is a snap and allows you to speed-up end user interaction with pages.  I personally like the fact that successful AJAX calls can easily be routed to callbacks without having to worry about wiring up any helper JavaScript objects.

 

Logo

For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit www.thewahlingroup.com/.

Minimize Code by Using jQuery and Data Templates

I’m currently working on a heavily AJAX-oriented ASP.NET MVC web application for a business client and using jQuery to call controller actions, retrieve JSON data and then manipulate the DOM to display the data. Several of the pages have quite a bit of dynamic HTML that has to be generated once a JSON object is returned from an MVC controller action which generally leads to a lot of custom JavaScript.  After working through my first page on the project I realized that I was creating a maintenance nightmare due to the amount of JavaScript being written and decided to look into other options.

The first thing I looked for was some type of JavaScript template that would work much like GridView templates in ASP.NET.  I wanted to be able to define a template in HTML and then bind a JSON object against it.  That way I could easily tweak the template without having to actually touch my JavaScript code much.  I found several potential template solutions (and Microsoft will be releasing a nice option with ASP.NET 4.0 as well) that were nice but many were so CSS class centric that they ended up being a turn off since I felt like I had to learn yet another coding style just to use them.  I eventually came across one by John Resig (creator of jQuery and overall JavaScript genius) that was so small that I wasn’t sure it would even be viable.  I mean we’re talking tiny as far as code goes…so tiny that I figured it wouldn’t work well for what I needed.  After doing more searching and research I came across a post by my world famous buddy Rick Strahl (if you don’t currently follow his blog you won’t find a better one out there IMHO) that mentioned John’s micro template technique and had a few tweaks in it.  I tried it and was instantly hooked because it gave me the power to use templates yet still embed JavaScript to perform basic presentation logic (loops, conditionals, etc.) as needed.

The Template Engine (chipmunk power)

So here’s how the template works.  The first thing I did was add the template function as a jQuery extension so that I could get to it using familiar jQuery syntax.  This isn't required at all, it’s just something I wanted to do.  I ended up going with Rick’s slightly tweaked version and I only changed how the error was reported.  I’m not going to go into how to extend jQuery in this post, but here’s what the extension function looks like:

$.fn.parseTemplate = function(data)
{
    var str = (this).html();
    var _tmplCache = {}
    var err = "";
    try
    {
        var func = _tmplCache[str];
        if (!func)
        {
            var strFunc =
            "var p=[],print=function(){p.push.apply(p,arguments);};" +
                        "with(obj){p.push('" +
            str.replace(/[rtn]/g, " ")
               .replace(/'(?=[^#]*#>)/g, "t")
               .split("'").join("\'")
               .split("t").join("'")
               .replace(/<#=(.+?)#>/g, "',$1,'")
               .split("<#").join("');")
               .split("#>").join("p.push('")
               + "');}return p.join('');";

            //alert(strFunc);
            func = new Function("obj", strFunc);
            _tmplCache[str] = func;
        }
        return func(data);
    } catch (e) { err = e.message; }
    return "< # ERROR: " + err.toString() + " # >";
}

That’s all the code for the template engine.  Unbelievable really…runs on chipmunk power.

Creating a Template

Once the extension function was ready I had to create a template in my MVC view (note that this works fine in any web application, not just ASP.NET MVC) that described how the JSON data should be presented.  Templates are placed inside of a script tag as shown next (I chopped out most of the template to keep it more concise). 

<script id="MenuSummaryTemplate" type="text/html">
     <table style="width:100%;">
        <tbody>
            <tr>
                <td class="OrderHeader">Totals:</td>
            </tr>
            <tr>
                <td style="font-size:12pt;">
                    <table style="width:400px;">
                        <tr>
                            <td style="width:50%;">Sub Total:</td>
                            <td>$<span id="FinalSubTotal"><#= FinalSubTotal #></span></td>
                        </tr>
                        <tr>
                            <td>Sales Tax:</td>
                            <td>$<span id="FinalSalesTax"><#= FinalSalesTax #></span></td>
                        </tr>
                        <# if (DeliveryFee > 0) { #>
                        <tr>
                            <td>Delivery Fee:</td>
                            <td>$<span id="DeliveryFee"><#= DeliveryFee #></span></td>
                        </tr>
                        <# } #>
                        <tr>
                            <td>Admin Fee:</td>
                            <td>$<span id="AdminFee"><#= AdminFee #></span></td>
                        </tr>
                        <tr style="border-top:1px solid black;">
                            <td>Total:</td>
                            <td>$<span id="FinalTotal"><#= FinalTotal #></span></td>
                        </tr>
                        <tr>
                            <td colspan="2">&nbsp;</td>
                        </tr>
                        <tr>
                            <td colspan="2">Will be charged to your credit card ending with <#= CreditCard #></td>
                        </tr>
                    </table>
                </td>
            </tr>           <!-- More of the template would follow -->
        </tbody>
    </table>
</script>

You can see that the script block template container has a type of text/html and that the template uses <#=  #> blocks to define placeholders for JSON properties that are bound to the template. The text/html type is a trick to hide the template from the browser and I suspect some may not like that…you’re call though…I’m just showing one option.  The template supports embedding JavaScript logic into it which is one of my favorite features. 

After a little thought you may wonder why I didn’t simply update the spans and divs using simple JavaScript and avoid the template completely.  By using a template my coding is cut-down to 2 lines of JavaScript code once the JSON object is created (which you’ll see in a moment) and this is only part of the template. Here’s another section of it that handles looping through menu items and creating rows:

 

<#
   if (MainItems == null || MainItems.length == 0)
   {
#>
    <tr>
        <td>No items selected</td>
    </tr>
<#
   }
   else
   {
       for(var i=0; i < MainItems.length; i++)
       {
         var mmi = MainItems[i];
#>
        <tr>
           <td>
                <#= mmi.Name #>:  <#= mmi.NumberOfPeople #> ordered at $<#= mmi.PricePerPerson #> per person
           </td>
        </tr>
<#
       }
   }
#>


Binding Data To a Template

To bind JSON data to the template I can call my jQuery extension named parseTemplate(), get back the final HTML as a string and then add that into the DOM.  Here’s an example of binding to the template shown above.  I went ahead and left the JSON data that’s being bound in so that you could see it, but jump to the bottom of LoadApprovalDiv() to see where I bind the JSON object to the template….it’s only 2 lines of code.

function LoadApprovalDiv()
{
    var subTotal = parseFloat($('#SubTotal').text());
    var salesTaxRate = parseFloat($('#SalesTaxRate').val()) / 100;
    var salesTaxAmount = subTotal * salesTaxRate;
    var deliveryFee = parseFloat($('#DeliveryFee').val());
    var adminFee = (subTotal + salesTaxAmount + deliveryFee) * .05;
    var total = subTotal + salesTaxAmount + deliveryFee + adminFee;
    var deliveryAddress = $('#Delivery_Street').val() + ' ' + $('#Delivery_City').val() +
                          " " + $('#Delivery_StateID option:selected').text() + ' ' + $('#Delivery_Zip').val();
    var creditCard = $('#Payment_CreditCardNumber').val();
    var abbrCreditCard = '*' + creditCard.substring(creditCard.length - 5);

    var json = {
                   'FinalSubTotal'  : subTotal.toFixed(2),
                   'FinalSalesTax'  : salesTaxAmount.toFixed(2),
                   'FinalTotal'     : total.toFixed(2),
                   'DeliveryFee'    : deliveryFee.toFixed(2),
                   'AdminFee'       : adminFee.toFixed(2),
                   'DeliveryName'   : $('#Delivery_Name').val(),
                   'DeliveryAddress': deliveryAddress,
                   'CreditCard'     : abbrCreditCard,
                   'DeliveryDate'   : $('#Delivery_DeliveryDate').val(),
                   'DeliveryTime'   : $('#Delivery_DeliveryTime option:selected').text(),
                   'MainItems'      : GenerateJson('Main'),
                   'SideItems'      : GenerateJson('Side'),
                   'DesertItems'    : GenerateJson('Desert'),
                   'DrinkItems'     : GenerateJson('Drink')
               };

       var s = $('#MenuSummaryTemplate').parseTemplate(json);
       $('#MenuSummaryOutput').html(s);
}


You can see that I call parseTemplate(), pass in the template to use and JSON object and then get back a string.  I then add the string into a div with an ID of MenuSummaryOutput using jQuery.  Here’s a sample of what the template generates:


 image


Going this route cut down my JavaScript code by at least 75% over what I had originally and makes it really easy to maintain.  If I need to add a new CSS style or modify how things are presented I can simply change the template and avoid writing custom JavaScript code.  By using the template and AJAX calls I’ve been able to significantly minimize the amount of server code being written and meet the client’s requirement of having an extremely fast and snappy end user experience.  If you’re writing a lot of custom JavaScript currently to generate DOM objects I’d highly recommend looking into this template or some of the other template solutions out there.  I can’t say I’ve tested performance but can say that I’m working with some fairly large templates which are loading in < 1 second.  I personally feel it’s the way to go especially if you want to minimize code and simplify maintenance.  I think Microsoft’s entry into this area with ASP.NET 4.0 further validates the usefulness of client-side templates.

 

Logo

For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit www.thewahlingroup.com/.

Handling MouseEnter and MouseLeave Events in jQuery

I have a simple table generated by an ASP.NET MVC view and needed to switch out CSS classes as the user hovered over rows.  Initially I used the rather obvious “hover” feature built-into jQuery since it provides a way to write code that’s called as the user enters and leaves an object.  I ended up doing something like this:

$(this).closest('tr').hover(
    function()
    {
        $(this).addClass('Over');
    },
    function()
    {
        $(this).removeClass('Over');
});

While this works, I was looking into another scenario today and realized that it’s much easier to do the toggle effect using the jQuery bind() function combined with toggleClass().  Either way works, but I’m all for less code where possible.  Here’s how to achieve the same “hover” effect with less code:

$(this).closest('tr').bind("mouseenter mouseleave", function(e)
{
    $(this).toggleClass("Over");
});


The toggleClass() function automatically handles adding and removing the Over CSS class and the bind() function handles attaching to the mouseenter and mouseleave events.  Nice and clean…

 

Logo

For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit www.thewahlingroup.com/.

Selecting Parent Nodes using jQuery

Here’s a quick tip on selecting parent nodes based on something I had to do yesterday with jQuery on a client project.  I have an ASP.NET MVC page that outputs a basic table containing search results and as a user hovers over an item in a map I needed to highlight the appropriate row in the search results by changing its CSS class.  I debated simply adding an ID on the row to make it easy to find but decided I didn’t want to deal with another ID in the DOM.  Here’s what a portion of the view page looks like: 

<tr>
    <td style="width:25%;">
        <span id='restID_<%= rest.RestaurantID %>' desc='<%= addr %>'
          class="Restaurant" lat='<%= rest.Address.Latitude %>' lon='<%= rest.Address.Longitude %>'>
            <%= rest.Name %>
        </span>
    </td>
    <td style="width:55%;">
        <span><%= addr %></span>
    </td>
    <td style="width:20%;">
        <%= Html.ActionLink("View Menu","Details","Menu") %>
    </td>
</tr>

On my first attempt I selected the target row the way I typically would do back in the day with plain old JavaScript (I guess we could call it POJ…those that know about POCO and similar terms will understand :-) ) which is to select the target span, move up to its parent (the td) and then move up to its parent (the tr).  This works fine, but I ended up going with the following to make it more flexible in case other parents nodes were introduced down the road in the HTML:

function PushPinOver(e)
{
    var shape = $(mapObj)[0].map.GetShapeByID(e.elementID);
    if (shape != null)
    {
        //Find restaurant and highlight it
        current = $('#' + shape.RestaurantID);
        current.parents('tr:eq(0)').addClass('Over');
    }
}

Notice that the last line of code uses the parents() method and says to look for the first tr tag parent (eq(0) filters it down to the first parent).  The code is much more flexible compared to what I originally had especially if I decide to add other tags into the table cells.  As the user hovers off of a map item I then call the following code to locate the same tr parent and remove the CSS class:

function PushPinOut(e)
{
    var shape = $(mapObj)[0].map.GetShapeByID(e.elementID);
    if (shape != null)
    {
        //Find restaurant and highlight it
        if (current != null) current.parents('tr:eq(0)').removeClass('Over');
        current = null;
    }
}

jQuery provides a lot of different options for selecting objects which is why I like it so much….selectors rule!  I’ve cut down my JavaScript coding by at least 50-60% I’d guess as a result of using it.

Update: Another way to do this is to use the closest() method: current.closest(‘tr’)… which is even easier and I like it more for my particular scenario.  Thanks to Raj for commenting about that.

5 Reasons You Should Take a Closer Look at ASP.NET MVC

I’m an ASP.NET Web Forms fan…always have been since ASP.NET was first released.  But, I like to keep an open mind when it comes to new technologies and I decided to experiment with the new ASP.NET MVC framework that Microsoft just released so I knew how it could be used with consulting projects and for training my company provides.  I was so impressed with some of the things I could do that I’m now using ASP.NET MVC 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 personally think you should look at ASP.NET MVC and see if it can benefit your projects at all. 

In this post I’m going to outline 5 things I really like about ASP.NET MVC and separation of concerns, unit testing, complete control over HTML, etc. aren’t going to be covered.  If you want those things you get them too so keep that in mind before yelling, “You didn’t mention testing Dan!”.  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 get more 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 the sake of 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..wasn’t 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" />&nbsp;&nbsp;
            <span class="StatusMessage" style='color:<%= Model.StatusColor %>'><%=Model.StatusMessage %></span>
        </td>
    </tr>
</table>

The first thing you’ll notice is that controls are defined differently in ASP.NET MVC then they are in ASP.NET Web Forms.  That’s a topic for a later post so I’m not going to focus on controls here.  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”!).  But…I digress.  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”…case 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.

[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

Views display the data given to them by Controllers as mentioned earlier.  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:

image

This saves a tremendous amount of time 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 FilesMicrosoft Visual Studio 9.0Common7IDEItemTemplatesCSharpWebMVCCodeTemplates by default.  For example, if you prefer tables for your forms you could tweak one of the template files such as Edit.tt as shown next:

        <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

image 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 AjaxHelper (shown earlier) object’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’ll 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 forces gently 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. 

To Sum Up….

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 post has given you a few reasons to research the ASP.NET MVC framework more 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’m really liking the control that ASP.NET MVC gives you.

 

 

Logo

For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit www.thewahlingroup.com/.

Reflecting over JSON Data to Simplify Control Updates with jQuery

My company is currently working on a consulting project that uses ASP.NET MVC and a lot of jQuery and JSON behind the scenes for data transfer which is a lot of fun.  I’m personally tasked with the back-end processes but also handling user interface updates as JSON data is received.  I have a form with several different controls in it that are updated once JSON is returned from a controller action and the controls are updated using jQuery selectors.  Something like this:

$('#OfficeProfile_CustomerID').val(json.OfficeProfile.CustomerID);
$('#OfficeProfile_OfficeProfileID').val(json.OfficeProfile.OfficeProfileID);
$('#OfficeProfileAddress_AddressID').val(json.OfficeProfile.AddressID);
$('#OfficeProfile_OfficeTitle').val(json.OfficeProfile.OfficeTitle).convertNullToEmptyString();
$('#OfficeProfile_OfficeContactName').val(json.OfficeProfile.OfficeContactName).convertNullToEmptyString();
$('#OfficeProfile_NumberOfPeople').val(json.OfficeProfile.NumberOfPeople).convertNullToEmptyString();
$('#OfficeProfile_Phone').val(json.OfficeProfile.Phone).convertNullToEmptyString();
$('#OfficeProfile_Comments').val(json.OfficeProfile.Comments).convertNullToEmptyString();
$('#OfficeProfileAddress_Street').val(json.OfficeProfile.Address.Street).convertNullToEmptyString();
$('#OfficeProfileAddress_City').val(json.OfficeProfile.Address.City).convertNullToEmptyString();
$('#OfficeProfileAddress_StateID').val(json.OfficeProfile.Address.StateID).convertNullToEmptyString();
$('#OfficeProfileAddress_Zip').val(json.OfficeProfile.Address.Zip).convertNullToEmptyString();

While this code works fine, it quickly becomes a pain as JSON properties change and it’s just too much typing for my taste.  I decided that there must be a more compact way to do this given that there’s definitely a pattern to the ID names used in the jQuery selectors and the value assigned to each control.  After thinking about it more I realized that I need to use “reflection” (a technique used to inspect objects in the .NET framework) to access the JSON properties and then handle updates to the controls.  But, how do you reflect over a JSON object and figure out what properties it has?  Turns out it’s pretty easy…after a quick Google/Live search anyway.  You can iterate through the JSON object’s properties using a normal JavaScript for loop and then access each property name and value.  Here’s what I ended up doing to simplify the code above and make it more dynamic:

var prefix = '#OfficeProfile_';
var addrPrefix = '#OfficeProfileAddress_';
for (prop in json.OfficeProfile)
{
    var propVal = json.OfficeProfile[prop];
    if (prop == 'Address') //Object property within JSON..loop through Address object properties
    {
        for (addrProp in propVal)
        {
            $(addrPrefix + addrProp).val(propVal[addrProp]).convertNullToEmptyString();
        }
    }
    else
    {
        $(prefix + prop).val(propVal).convertNullToEmptyString();
    }
}

The json variable in the previous code represents the JSON returned from the call to the server and it exposes an OfficeProfile property.  The code loops look through each property in the OfficeProfile object, stores the value and then uses the property name to locate the appropriate control within the form that I want to update (using jQuery selector syntax).  I suspect there’s additional refactoring that I could apply but has worked out nicely so far.

 

Logo

For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit www.thewahlingroup.com/.

WP Like Button Plugin by Free WordPress Templates