Oct 22 2009

Simplify jqGrid JSON Generation

Category: .Net Framework | Web DevelopmentAlexRobson @ 15:09

So I’m trying to learn this jqGrid thing and so far it seems pretty cool but one thing was really bothering me: every example I saw that was using JSON was using anonymous types to create the required JSON format. Yuck city. Yes. I’m insane and whiney but there’s method to my madness.

Here’s the anonymous type approach:

var jsonData = new
{
    total = totalPages,
    page = page,
    records = totalRecords,
    rows = (
        from record in records
        select new
        {
            i = record.Id,
            cell = new string[] {
               record.Name, 
                record.Date.ToShortDateString(), 
                record.Description.ToString() 
            }
        }).ToArray()
};

Imagine you have to change any of these properties or the “schema” of your JSON output. What if you had to do that application wide? No refactoring tool can save you. Not only that, but you have to memorize/lookup the schema every time you create it. Typos will ruin you but there’s no compile time checking. These are just a few of the reasons I really dislike that approach.

What if you could do this instead?

var gridData = new jqGridData<Task>(
                tasks, 
                t => t.Id, 
                t => new object[]
                       {
                           t.Name,
                           t.Date,
                           t.Description
                       })
                       {     
							page = 1, 
							total = tasks.Count/pageSize,
							records = tasks.Count};

Now that’s more like it. Strongly typed, intellisense, compile time checked and refactor friendly. So here’s the code to make it happen (it’s very simple):

public class jqGridData<T>
	where T : class
{
	public int total { get; set; }
	public int page { get; set; }
	public int records { get; set; }
	public IList<jqGridRow<T>> rows { get; set; }

	public jqGridData(IList<T> list, Func<T, object> idMember, Func<T, object[]> columns)
	{
		rows = list.Select(i => new jqGridRow<T>(i, idMember, columns)).ToList();
	}
}
	
public class jqGridRow<T>
	where T : class
{
	public string id { get; set; }
	public string[] cell { get; set; }
	
	public jqGridRow(T rowInstance, Func<T, object> idMember, Func<T, object[]> columns)
	{
		id = idMember(rowInstance).ToString();
		cell = columns(rowInstance).Select(c => c.ToString()).ToArray();
	}
}

Right, not an earth-shattering discovery, certainly not going to change your life, but it does make using jqGrid with JSON simple.

Tags: ,

Oct 16 2009

ASP.Net MVC 2 Preview 2 Installation Issue

Category: .Net Framework | Web DevelopmentAlexRobson @ 09:28

Thanks to some help from Elijah Manor, I was ready to pull down the Preview 2 installer for ASP.Net MVC 2 and play around with the new features over the week-end. Long story short; there are some people born lucky, and I am not one of them. The installer kept tanking hard telling me that I was missing important system updates and that the installer couldn’t continue without those. Say what?

After messing around for a bit, I remember having other issues due to my (foolish?) decision to install the VS 2010 beta on the same machine as VS 2008 (instead of in a VM like Evan Hoff did). So I started looking through my installed items and saw that MVC 1.1 is the VS 2010 compatible version. After uninstalling that MVC 2 Preview 2 installed without a hitch.

The happy end to this story is that you can go back and re-install MVC 1.1 for VS 2010 once the Preview 2 installation has completed without any other issues. HTH.

Tags: , ,

Jul 30 2009

Using jQuery To Control ASP.Net Client Side Validation

Category: Web DevelopmentAlexRobson @ 00:36

I recently had to add functionality to a ASP.Net 3.5 web form of ours that allowed a user to provide a suggested alternative when the value they needed wasn’t available in a drop down box. To do this, I wanted to be able to turn our client side validation on and off for the controls involved.

One of the things we did early on in this project was to create a set of user controls which wrap labeling, watermarking, validation and some other features to the usual set of ASP.Net form controls. This simplifies our mark-up considerably by encapsulating several server controls into one user control that’s configurable through attributes. All these super controls also have client-side validation enabled (and in some cases, custom implemented) so that it’s nearly trivial to develop a solid form view/list view rather quickly.

Since we’re using as much out-of-the-box functionality as we can for the client side validation, I didn’t want to have to go outside of our normal pattern to provide the desired functionality. So when the user was going with an value in the drop down, I needed the client-side validation for the suggestion text box turned off, but if the user selected the “Other” option in the drop down, I’d reveal the suggestion text box and turn on the client side validation… this took me a while to figure out and I didn’t really find much in the way of documentation to help me. (perhaps there’s a better way? if so, let me know)

Since I wasn’t finding much in the way of help, I simply started digging through the javascript sent to the browser for the form. What I found (after lots of digging) is that the standard validation controls in ASP.Net get added to an array during page initialization.

var validatorControl = document.getElementById("validationControlClientId");
// some initialization happens over several lines
Array.add(Page_Validators, validatorControl);

The take-away being that there’s an array of the validator controls which the validation script uses to run through to evaluate all the client side validation pre-submit. Since we’re generating all these controls as part of a larger user control, I knew the naming convention that was used for the validation controls.

All I had to do then was:

  1. Get the client id for the control I wanted to toggle validation for
  2. Formulate the client id for the validation control
  3. Add/Remove the validation control from the Page_Validators array

Now, I know a lot of people get very particular about how you select elements from HTML and that you don’t want it to be so brittle that anyone making harmless changes to the page later could break your jQuery. What I did was to add superficial css classes to the container for the super control so I could get the client id, then I wrote a simple function that would turn client-side validation on or off for that type of control.

var suggestedText = $("input.Suggestion");

function ToggleTextBoxValidation(control, enabled)
{
    // the rqf prefix is for Required Field
    var id = control.attr("id").replace("textbox", "rqfText")
    // gets the actual ASP.Net validator control
    var validator = document.getElementById(id);

    if (enabled) {
        Array.add(Page_Validators, validator);
    }
    else {
        Array.remove(Page_Validators, validator);
    }
}

So this is obviously a fairly watered down version from what I have in my page but hopefully this illustrates clearly enough how you can turn ASP.Net client side validation on or off using jQuery.

kick it on DotNetKicks.com

Tags: , ,