1. 程式人生 > 實用技巧 >How to pass a value to razor variable from javascript variable?

How to pass a value to razor variable from javascript variable?

How to pass a value to razor variable from javascript variable?

回答1

You can't. and the reason is that they do not "live" in the same time. The Razor variables are "Server side variables" and they don't exist anymore after the page was sent to the "Client side".

When the server get a request for a view, it creates the view with only HTML, CSS and Javascript code. No C# code is left, it's all get "translated" to the client side languages.

The Javascript code DO exist when the view is still on the server, but it's meaningless and will be executed by the browser only (Client side again).

This is why you can use Razor variables to change the HTML and Javascript but not vice versa. Try to look at your page source code (CTRL+U in most browsers), there will be no sign of C# code there.

In short:

  1. The server get a request.

  2. The server creates "takes" the view, compute and translate all the C# code that was embedded in the view, to CSS,Javascript, and HTML.

  3. The server returns the client side version of the view to the browser as a response to the request.
  4. the browser renders the page and executes all the Javascripts

回答2

But it would be possible if one were used in place of the variable in @html.Hidden field. As in this example.

@Html.Hidden("myVar", 0);

set the field per script:

<script>
function setMyValue(value) {
     $('#myVar').val(value);       
}
</script>

I hope I can at least offer no small Workaround.