Wednesday, August 25, 2010

How to access server side control values using java script and change in the client side - Part 2 [ UserControl or WebControl]

To inject control ClientID values to the script for in WebControl or UserControl we can register script dynamically using this.Page.ClientScript.RegisterClientScriptBlock(...) method.
Example:
<%@ Control Language="C#" 
            AutoEventWireup="true" 
            CodeBehind="WebUserControl.ascx.cs" 
            Inherits="ActiveTest.WebUserControl" %>
<script runat="server">
    string script = @"
            function GetValue() {{
                var input = document.getElementById('{0}');
                alert(input.value);
                return false;
            }}
            function SetValue() {{
                var value = prompt(""Input Value"", ""BMW"");
                var input = document.getElementById('{1}');
                input.value = value;
                return false;
            }}
            function TransferValue() {{
                var input1 = document.getElementById('{0}');
                var input3 = document.getElementById('{2}');
                input3.value = input1.value;
                return false;
            }}
        ";
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        this.Page.ClientScript.RegisterClientScriptBlock(
                this.GetType(),
                this.GetType().Name,
                string.Format(this.script, this.txtValue1.ClientID, this.txtValue2.ClientID, this.txtValue3.ClientID),
                true);
    }    
</script>
<div id="Control">
    <h4>Get Value</h4>
    <asp:TextBox runat="server" ID="txtValue1" Text="Toyota" />
    <asp:Button runat="server" ID="btnGetValue" Text="Get Value" OnClientClick="javascript:return GetValue()" />
    <hr />
    <h4>Set Value</h4>
    <asp:TextBox runat="server" ID="txtValue2" />
    <asp:Button runat="server" ID="btnSetvalue" Text="Set Value" OnClientClick="javascript:return SetValue()" />
    <hr />
    <h4>Transfer Value</h4>
    <asp:TextBox runat="server" ID="txtValue3" />
    <asp:Button runat="server" ID="btnTransferValue" Text="Transfer Value" OnClientClick="javascript:return TransferValue()" />
</div>

No comments:

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...