如何从JavaScript变量值传递给剃须刀变量? [英] How to pass a value to razor variable from javascript variable?

查看:145
本文介绍了如何从JavaScript变量值传递给剃须刀变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从JavaScript变量值传递给剃须刀变量,这可能asp.net的MVC的Razor视图引擎?



  @ {
INT A = 0;
}

<脚本>
变种B = ...
@a = B;
< / SCRIPT>


解决方案

您不能。其原因是它们不活在相同的时间。
剃刀变量是服务器端变量,他们不存在了之后,页面被送到客户端。



在服务器得到一个视图的请求时,它会创建只有HTML,CSS和JavaScript代码视图。没有C#代码留,这一切都得到翻译到客户端语言。



JavaScript代码是存在的,当观点仍然在服务器上,但它的意义并将由浏览器只(客户端再次)执行的。



这就是为什么你可以用剃刀变量来更改HTML和Javascript而不是相反。试着在你的页面的源代码查找(CTRL + U在大多数浏览器),将没有的C#代码有迹象



在短:




  1. 服务器获取请求。


  2. 服务器创建取看来,计算和翻译都被嵌入在视图中的C#代码,CSS,Javascript和HTML。


  3. 服务器返回的视图的客户端版本到浏览器作为对请求的响应。

  4. 浏览器呈现的页面并执行所有的Javascript


How to pass a value to razor variable from javascript variable, is it possible asp.net mvc razor view engine?

@{
    int a = 0;
}

<script>
    var b = ...
    @a = b;
</script>

解决方案

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

这篇关于如何从JavaScript变量值传递给剃须刀变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆