JQuery id with unauthorised characters

Yesterday was the second time I’ve found myself staring at the screen trying to figure out what just went wrong there, which in my book is the best trigger for writing a post. The problem is very simple:

In ASP.NET MVC, in order to get a collection (list/array/dictionary etc’) property of your view-model out back to the controller, you need to have your TextBox (or whatever) id attribute looking like this:

<input ... id="MyList[0].Name" ... />

More about it can be found here. Now, all is working nice and tidy until you bring JQuery in, which will not let you select such an object by its id (or any id that contains selector characters such as ‘.’, ‘:’ and so on) , so that the following code will return null:

$("#MyList[0]_Name")

My almighty, kind and generous boss has came up with a bit of code that will override this behviour, which I took liberties to refactor in order to take care of the ‘.’ and ‘:’ cases (even though dots shouldn’t really be a part of the id since the HtmlHelper extension methods in MVC replace dots with an underscore)-

function $$(selector, context) {
 return jQuery(selector.replace(/(\[|\]|:|\.)/g, '\\$1'), context)
}

So that all you need to do is:

$$("#MyList[0]_Name")

tidy! 🙂

Advertisements
Explore posts in the same categories: ASP.NET MVC, JQuery

Tags: ,

You can comment below, or link to this permanent URL from your own site.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: