How to access JS variable in C#

Let’s say I have

<div id="blah">500</div>

(Context: asp.net aspx page)
How do I allow a c# code access that value?

<%
    int numberiwant = ###; // Ideally 500
%>

I was thinking of something along the lines of jQuery:

<script type="text/javascript">
var value = $('#blah').html();
// Then do some magic and pass to c#?
</script>

Is there a better way?

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

Use a hidden input box

<input id="hiddenControl" type="hidden" runat="server" />

Put your value in the input box with javascript

//call this method before you postback, maybe on form submit
function SetPostbackValues() {
  var hiddenControl = '<%= hiddenControl.ClientID %>';
  document.getElementById(hiddenControl).value = 500; 
  //or some other code to get your value
}

Access the value with the input box on the server side

protected void btnSubmit_Click(object sender, EventArgs e) {
   var hiddenValue = hiddenControl.Value;
}

Method 2

You can use a server-side div instead, like i.e;

<asp:Panel ID="blah" runat="server">500</asp:Panel>

Then you can access it and its contents server-side.

Alternatively;

<div id="blah"><asp:Literal ID="blahContent" runat="server" Text="500" /></div>

UPDATE: After the question was clarified, it is clear this won’t work. The only solution then is to use javascript to get the value, then AJAX to send it to the server.

Method 3

The C# code inside <% .. %> is run on the server when the HTML is generated. When the value updates via AJAX, it all happens on the client – long after the C# has finished running.

Method 4

Server side won’t ever have direct access to client’s variables (javascript). You have to send them to the server somehow, either via query or post, or through AJAX.


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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x