0

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

enter image description here

Code C#

enter image description here

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

0

You can keep it in hidden input field and access that hidden field value in JavaScript.

Comments

0

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;

2 Comments

I believe this will work with the exception of the call to getElementById('hfVariable'), I believe it should be getElementById('<%= hfVariable.ClientID %>').
@tdinpsp Yes, you're right. Actually, I forgot about that. Thank you. I corrected my mistake.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.