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 http://www.thewahlingroup.com/.

Published Monday, April 06, 2009 1:07 PM by dwahlin
Filed under: , , ,

Comments

# ASP.NET MVC Archived Blog Posts, Page 1

Monday, April 06, 2009 5:42 PM by ASP.NET MVC Archived Blog Posts, Page 1

Pingback from  ASP.NET MVC Archived Blog Posts, Page 1

# re: Reflecting over JSON Data to Simplify Control Updates with jQuery

Monday, April 06, 2009 7:37 PM by Steve

You could probably do the "address" field checking by generically checking if the json data is an object (array), in which case you dive in.

# re: Reflecting over JSON Data to Simplify Control Updates with jQuery

Monday, April 06, 2009 7:42 PM by dwahlin

That's a good idea and something I experimented with a little bit.  I realized that if I added any other nested objects it would cause problems potentially so I opted to leave "Address" in there to make sure only it would be processed like that

# re: Reflecting over JSON Data to Simplify Control Updates with jQuery

Monday, April 06, 2009 8:11 PM by Mike

>thanks for a nice tip

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

Monday, April 06, 2009 9:56 PM by Dan Wahlin's WebLog

I’m an ASP.NET Web Forms fan…always have been since ASP.NET was first released.  But, I like to

# Dew Drop - April 7, 2009 | Alvin Ashcraft's Morning Dew

Tuesday, April 07, 2009 8:38 AM by Dew Drop - April 7, 2009 | Alvin Ashcraft's Morning Dew

Pingback from  Dew Drop - April 7, 2009 | Alvin Ashcraft's Morning Dew

# re: Reflecting over JSON Data to Simplify Control Updates with jQuery

Tuesday, April 07, 2009 4:48 PM by Liam McLennan

If your JSON object has inheritance or functions then you need to check for those conditions with json.OfficeProfile.hasOwnProperty('prop') and typeof propVal !== 'function' respectively.

# re: Reflecting over JSON Data to Simplify Control Updates with jQuery

Tuesday, April 07, 2009 7:11 PM by dwahlin

Liam,

Thanks for the tip...good to know.  In this case it's pure properties, but hasOwnProperty would be very useful for objects that do have associated functions.

Dan