I have a jqueryscript that works with asp.net pages without masterpages. When the page gets an reference to a masterpage the script stop working.
The masterpage:
Within the header:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
At codebehind:
protected void Page_Load(object sender, EventArgs e)
{
string script = "$(document).ready(function () { $(\"img[src*='help']\").click(function () { var id = $(this).attr(\"id\"); $(\"#helpviewer\").toggle(400); $(\"#helpviewer\").load(\"" + Page.ResolveUrl("~/help/help.aspx") + " \" + \"#\" + id); return false; }); });";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), script, true);
}
Here is the helppage that jquery loads:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="help.aspx.cs" Inherits="help_help" meta:resourcekey="PageResource1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div id="helpUploadFile">
<asp:literal id="Literal1" runat="server" meta:resourcekey="Literal1Resource1"></asp:literal>
</div>
<div id="helpPictureArchive">
<asp:literal id="Literal2" runat="server" meta:resourcekey="Literal2Resource1"></asp:literal>
</div>
<div id="image1">
<asp:literal id="Literal3" runat="server" meta:resourcekey="Literal3Resource1"></asp:literal>
</div>
</form>
</body>
</html>
I belive my problem lies in the .load. The script is working, the helpviewer is shown up but the text is not loading.
Here is a working testpage without masterpage. and here is a testpage with the masterpage. Just click at the image to se the jquery.
Any idea whats wrong?
IDs in master pages (or any other container) get mangled due to the way naming containers work, so I like to reference my server controls using jQuery’s ends with selector:
Since the mangled IDs always have the control name on the right, this just works. The mangled ID would look something like this: MasterPage1_ctl02_MyControlName
I’ve seen some people criticize this approach as relatively slow compared to concatenating in Control.ClientID, which is how I used to do it. But avoiding Control.ClientID means you can store your JavaScript in a seperate file, which is a best practice. Sometimes, if you’re getting extremely dynamic, doing JS on the server is unavoidable. But in a seperate file you’ve got better seperation of concerns, and Visual Studio gives you some intellisense, and so on.
Here’s a related question: jQuery Selector: Id Ends With?
More about naming containers: MSDN Article