How can I pass a javascript value to asp.net variable?

How can I pass a javascript value to asp.net variable?

Run Sample | Download Source

You can take following steps to read value from javascript.

1. Create html hidden field on page.
2. Set its value on client side using javascript.
3. Read html hidden field using Request.Forms["hiddenfieldname"]

Following sample code shows how to achieve that functionality


<%@ Page Language="C#" %>
<script runat="server">
    
string servervariable;
    
    void 
ServerBtn_Click(object sender, EventArgs e)
    {
        servervariable 
Request.Form["Hidden1"];
        
MessageField.Text servervariable;
    
}
</script>
<head runat="server">
    
<title></title>
</head>
<body>
    
<p>
        Following sample demonstrates a way to pass value from 
        javascript function to asp.net.
     
</p>  
     
<p>  
        Since javascript function does not have access to 
        server side code we have to store value in
        hidden field and then read hidden field value 
        from server side code.
    
</p>
    
<form id="form1" runat="server">
    
<div>
        
<input id="Hidden1" name="Hidden1" type="Hidden" 
            runat
="server" value="old value" />
        <
input type="button" 
            onclick
="alert(document.getElementById('Hidden1').value)" 
            value
="Read Value From Client">
         
        
<input type="button" 
            onclick
="document.getElementById('Hidden1').value = 'New Value'" 
            value
="Set Value From Client"> 
         
        
<asp:Button runat="server" ID="ServerBtn" 
            OnClick
="ServerBtn_Click" Text="Read Value From Server Side" />    
    </
div>
    
<p>
        
<asp:Literal runat="server" ID="MessageField" />
    </
p>
    
</form>
</body>
</html>


Bookmark with:
Technorati   Digg   Delicious   StumbleUpon   Facebook
My name is Jigar Desai I share my ideas on this site and you can contact me by filling contact form.

Categories