user3321263
user3321263

Reputation: 45

Assign javascript variable to C# variable (ASP.net)

I know that I can assign C# variable to js like that:

<script >
var x = <%=CsharpVar%> ;
</script>

that's work.

but there is option to do the opposite? I mean something like that (It's not working for me):

<script >
var x= "Exmp";
<%CsharpVar=%>=x ;
</script>

Thank you!

Upvotes: 1

Views: 3542

Answers (2)

Jonathan Anctil
Jonathan Anctil

Reputation: 1037

To assign a javascript value to C# variable, you can use hidden field with attribute runat=server and get this value server side.

Another solution like SLC wrote, is to send the value to server. I already did that using httphandler + ajax call to store entered value in server session state and reusing server side.

Upvotes: 0

NibblyPig
NibblyPig

Reputation: 52952

This is not possible, because you have to consider how pages are generated in asp.net

The server generates the page, then pushes it to the client. Therefore it can add c# variables into the page and do other stuff, but once it's pushed, it can no longer interact.

The only way to get data back from the javascript code into the C# is to send it to the server.

So for example, if a user fills in a textbox on a form, they have to press submit so it is pushed to the server before the server knows anything about it. They are completely disconnected, and the only communication that can occur between the page and the server is when it specifically sends a request (eg. submitting a form).

When a form or similar is submitted, the page will send the server something like 'load the update profile page, and the name i put in the textbox is dave' then the server can figure out what to do with the data it received, eg. update the person's name to 'dave'.

If you want to be more dynamic, you can use ajax to update something without refreshing the whole page. Many websites do this when you're updating settings, eg. you click a checkbox to do something, it will perform an ajax request (basically the same as the above example, but it happens quietly in the background).

Either way you need to spend a bit of time understanding how asp.net works under the hood I think to properly understand what's going on and why you can't do what you're trying to do. The easiest way to think of it is that when the server displays your page and sends it to you, it puts it into a box and fedex's it to your house. If you do anything with it then the server isn't going to have a clue, or be able to put anything into C# variables etc. unless you make all your changes, and fedex it back.

Upvotes: 3

Related Questions