How to get c# code behind variable value in javascript?
I have declared a variable in page load.
I want that variable value in javascript.
Javascript
Code C#
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Needs to be at the class level. As your code is now, by the time the page is being rendered that variable is long gone out of scope
public class Whatever{
public string OrderID { get; set; }
Make it a property too, if your plan is for it to be public as your naming (capital O) implies
Method 2
You can keep it in hidden input field and access that hidden field value in JavaScript.
Method 3
You cannot interact between client-side and server-side without sending an HTTP request to the server.
you cannot assign as javascript variable directly to the code-behind.
what you can do is like
create a hidden field variable in the client side as
<asp:HiddenField ID="hfVariable" runat="server" />
and in the javascript, you can assign some value to the hidden variable as
<script type="text/javascript">
var somefunction = function () {
var hfVariable = document.getElementById('<%= hfVariable.ClientID %>');
hfVariable.value = 'value';
}
</script>
and you can read the hidden field variable in the code behind as
string variable = hfVariable.Value;
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

