Click here to Skip to main content
15,890,982 members
Please Sign up or sign in to vote.
3.67/5 (2 votes)
See more:
I have searched around for how to Pass javascript variable's value to C# code behind, but have not got no good result. The key is how to assign an object ID to the variable and then its value can be passed to C# code behind. Appreciate if you can share your experience.
Posted
Comments
Karthik_Mahalingam 9-Jan-14 13:07pm    
post your code..
Mohammad Reza Emami Zadeh 11-Oct-15 9:30am    
test

You cannot interact between client side and server side without sending and HTTP request to the server. You can do it using Ajax:
http://en.wikipedia.org/wiki/Ajax_%28programming%29[^].

One convenient way of using Ajax is using jQuery .Ajax(): http://api.jquery.com/jquery.ajax/[^].

—SA
 
Share this answer
 
As Sergey said you cannot assign as javascript variable directly to code behind,
what you can do is like

create a hidden field variable in the client side as

ASP.NET
<asp:HiddenField ID="hdnfldVariable" runat="server" />


and in the javascript you can assign some value to the hidden variable as

JavaScript
<script type="text/javascript">
        var somefunction = function () {
            var hdnfldVariable = document.getElementById('hdnfldVariable');
            hdnfldVariable.value = 'value from javascript';
        }
    </script>


and you can read the hidden field variable in the code behind as

C#
string variable = hdnfldVariable.Value;
 
Share this answer
 
Comments
[no name] 9-Jan-14 13:36pm    
Since I use dojo, I have to use HTML controls. If I use ASP.Net control, get error:
Control 'Button1' of type 'Button' must be placed inside a form tag with runat=server.
Any hint to solve this conflict? Thanks.
Paramaa 9-Jan-14 14:01pm    
Do you try this change <form> tag to <form runat="server"> ?
Member 10531790 5-Jun-15 9:38am    
ik
[no name] 9-Jan-14 14:07pm    
Yes. In my another thread: http://www.codeproject.com/Questions/708621/System-Web-UI-Page-Request-Not-there, I got NullException. Could you help on that one? Thanks.
Karthik_Mahalingam 10-Jan-14 0:05am    
replied over there, pls chk it.
Thanks
karthik

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900