Jquery is a great javascript library, although it has a significant drawback when used in ASP.NET web applications. Because of the way ASP.NET translates it’s own internal identifiers to html id and name attributes, you cannot really use it in static javascript files.

A typical example would be:

<asp:TextBox runat="server" ID="tbName">

Which would be rendered to html as:

<input id="ctl00_cphMain_ucContact_tbName" name="ctl00$cphMain$ucContact$tbName" type="text" />

This overly verbose id, makes it very difficult to reference elements, in this case you would use the following code:

$("#ctl00_cphMain_ucContact_tbName").val("Evgeny");

This is less than ideal when it comes to writing scripts, therefore one quick method to simplify the process, is to place your js statements in aspx or ascx files and use tags like in this example:


<script type="text/javascript">
  $("#<%=tbName%>").val("Evgeny");
</script>

Apart from the method above, there are some other more complex techniques to reference ASP.NET elements from within static js files. I’ve developed a couple of jquery extensions to help with this:


$.expr[":"].id = function(el, i, match) {
  var x = $(el).filter("[id$=_" + match[3] + "]");
  if (x.length == 0) {
    return null;
  } else {
    return x;
  }
};
    
$.expr[":"].name = function(el, i, match) {
  var x = $(el).filter("[name$=$" + match[3] + "]");
  if (x.length == 0) {
    return null;
  } else {
    return x;
  }
};

For example, now I am able to refer to ASP.NET controls in the following ways:


$("input:id(tbName)").show().focus();
var val = $("input:name(rblConsultant)").filter(":checked").val();

Isn’t it cool? 

You may also like

Developing faster web forms in .NET

Quite often, we develop web forms containing heavy elements, in particular large select tags, which can be a bit of a problem. In this particular instance we are primarily referring to  ASP.NET MVC with normal html layout. Check out how we tackled this issue using AJAX and jQuery.

Keep Reading

Tips for Building Online Calculators

We recently had to change a superannuation calculator that Revium has developed for VicSuper.Whilst the changes were relatively small (caused by legislative changes), the implementation needed considerable care and attention.  This prompted me to document a few tips which others may find of use.

Keep Reading

Newsletter sign up

Every couple of months we send out an update on what's been happening around our office and the web. Sign up and see what you think. And of course, we never spam.