Powered by Blogger.

Sunday, February 23, 2014

Get control value using JavaScript with master page in Asp.Net



In this post we will discuss how to get control values using JavaScript with master page in Asp.Net. Also you can check out some of posts on:

- SET XACT_ABORT ON in sql server

- Body onload function in content page in asp.net

- Download Microsoft Enterprise Library 6 developer guide free

If you are trying to get a control value using JavaScript with Master page associated with it like below, then you will face some issue while rendering the page.

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <script type="text/jscript">
        function GetName() {
var name = document.getElementById('ContentPlaceHolder1_txtSequenceNumber').value;
   }
</script>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>

if you try to retrieve value by giving it id like:

txtName
or
ContentPlaceHolder1_txtName

Then while rendering sometimes the control id changed to  ctl00_ContentPlaceHolder1_txtName. So you will not get the proper value.

Actually when MasterPages are used they tend to rename all the controls in the content pages which have runat="server" attribute.

The best way to overcome this issue is to use ClientID property of the controls like below:

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <script type="text/jscript">
        function GetName() {
var name = document.getElementById("<%=txtName.ClientID%>").value;
   }
</script>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>





0 comments

Post a Comment