When you are using MasterPages your controls are rendered with Unique Client IDs in the browser. These ID's probably will not match the name that you have assigned them in your .NET code.
The reason this happens is because you can load several different pages into the ContentPlaceHol ders in the MasterPage. Each of these pages may have the same name for the .NET control.
For example take the following MasterPage:
-
<%@ Master Language="VB" Inherits="System.Web.Mvc.ViewMasterPage" %>
-
-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-
<html xmlns="http://www.w3.org/1999/xhtml">
-
<head runat="server">
-
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
-
<link href="Site.css" rel="stylesheet" type="text/css" />
-
</head>
-
-
<body>
-
<div id="main">
-
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
-
<asp:ContentPlaceHolder ID="FooterContent" runat="server" />
-
</div>
-
</div>
-
</body>
-
</html>
The above MasterPage has 3 ContentPlaceHol ders where you can place content. The first one, the TitleContent, is used to add stuff to the Header section of the page via the content pages using this MasterPage. The second, MainContent, will display the "main content" page, and the last one contains "footer content".
ASP.NET assigns each element within the content pages a unique ID in order to ensure that every element within the ContentPlaceHol ders gets a unique ID when it is rendered as HTML in the web browser.
So you may have a content page with a TextBox:
-
<asp:TextBox id="myTextBox" runat="server" />
But, because this content page is compiled along with the MasterPage the TextBox will end up with an HTML (clientID) of:
ctl00_MainConte nt_myTextBox
Or if it was in the footer ContentTemplate Holder it would look like:
ctl00_FooterCon tent_myTextBox
See how it works?
This is the ID that you need to use in your JavaScript.
The way to access this is to use the asp.net control's ClientID property.
So your JavaScript would look something like:
VB
-
var str=document.getElementById("<%= myTextBox.ClientID %>").value;
-
C#
-
var str=document.getElementById("<%= myTextBox.ClientID(); %>").value;
-
I was recently reading up on JavaScript loading times. Apparently it is best to place your JavaScript at the bottom of the page unless it NEEDS to be at the top (in the head section).
The reason is because of how things are rendered...if it's placed in the top of the page the the HTML and CSS has to wait to render while the JavaScript is being interpreted. But if you place it at the bottom of the page then the HTML and CSS can load quickly and then the JavaScript is interpreted.
So it's not bad to place it at the bottom of the page ...say in a Footer Section ;)