Things to remember while using jQuery with ASP.NET Master Pages

jQuery is great library but if not used properly then it can make you crazy. If you are using ASP.NET Master Page and planning to use jQuery as well then it is quite important to know few things otherwise your code is not going to work. I have prepared a checklist which you should remember or take care while using jQuery with ASP.NET Master Pages.

  • Ensure that if you have already include jQuery library in master page, then please don't include in Content Page.
  • The ASP.NET Master Page and Content Page gets merged into a single page when render in the browser. And browsers always executes the page from top to bottom. So remember, that jQuery code placed in Master Page will always gets executed first.
  • If you are using .NET 3.5 or below version then when Master pages are used then ID of the control placed in Content Page gets changed at run time. The Master Page ID is pre-pended to all controls on the content page. This is true only for control which have runat="server" attribute associated with them. So always use ClientID property to access control in jQuery.Below jQuery code access label element directly with its ID but this will fail.
    $('Label1').text();
    

    The correct way is,

    $('#<%=Label1.ClientID%>').text();
    

    So always use ClientID Property while accessing control in jQuery, if you are using Master Page. Also read "Useful jQuery code examples for ASP.NET Controls"

  • If you have include $(document).ready() in Master Page that doesn't mean that you can't include on Content Page. You can have many $(document).ready() blocks on your page. But remember it gets executed from top to bottom.
  • If you are using jQuery and Ajax with Master Page then please read "Use jQuery and Ajax together with ASP.NET Master pages"

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...