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

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

问题描述

如何将一个值从 javascript 变量传递给 razor 变量,是否可以使用 asp.net mvc razor 视图引擎?

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>

推荐答案

你不能.原因是他们不生活"在同一时间.Razor 变量是服务器端变量".并且在页面发送到客户端"后它们不再存在.

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".

当服务器收到一个视图请求时,它只用 HTML、CSS 和 Javascript 代码创建视图.没有留下任何 C# 代码,它都得到了翻译";到客户端语言.

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.

当视图仍在服务器上时,Javascript 代码确实存在,但它没有意义,只会由浏览器执行(再次是客户端).

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

这就是为什么您可以使用 Razor 变量来更改 HTML 和 Javascript,但反之则不行.尝试查看您的页面源代码(在大多数浏览器中为 CTRL+U),那里不会有 C# 代码的迹象.

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.

简而言之:

  1. 服务器收到请求.

  1. The server gets a request.

服务器创建或接受"视图,然后计算嵌入在视图中的所有 C# 代码并将其转换为 CSS、Javascript 和 HTML.

The server creates or "takes" the view, then computes and translates all the C# code that was embedded in the view to CSS, Javascript, and HTML.

服务器将视图的客户端版本作为对请求的响应返回给浏览器.(此时不再有 C#)

The server returns the client side version of the view to the browser as a response to the request. (there is no C# at this point anymore)

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

the browser renders the page and executes all the Javascript

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

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