[RESOLVED]set Javascript variable to razor

He, I would like to set Javascript variable to razor.

this code does not compile !!!

var userId = $('#hdId').val();
@{
     var userFromRazor = userId;
 }

regards.

Hi,

<div>

This sounds interesting. But looks like, it is not possible but reverse is possible due to the sequence of execution.

MVC Razor at server side (before sending to client), JS at client side.

http://stackoverflow.com/questions/11287484/using-javascript-variable-in-mvc3-razor-view-engine

Also, this makes worth to read, just to understand, why to separate js and razor code:

http://stackoverflow.com/questions/10460928/razor-if-inside-script-is-rejected-by-vs11

</div>

this is not possible. the server views (razor) job is to produce html that is downloaded to the browser. once the browser loads that html, it runs the javascript in the browser. the only way for javascript to send data back to the server is via a form post
or ajax.

because razor is producing the javascript source code, it can set a javascript variable to a value as sources code, but not realtime. so changing the variable after the html is produced will have no effect:

so

@{
    var hi = "hello";
}

<script>
  var hi = "@hi";
</script>

will produce the html:

<script>
  var hi = "hello";
</script>

which when the browser loads the html will execute the javascript. the browser know nothing about the server variable "hi", and the server really knows nothing about the javascript variable hi either.  

Leave a Reply