zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    用户模板和用户场景
    移动端疫情展示
    数据爬取
    全国疫情统计可视化地图-第二、三阶段
    学习进度条-第三周
    学习进度条-第二周
    软件工程第二周开课博客
    返回一个整数数组中最大子数组的和
    JavaWeb选课系统(2)
    JavaWeb选课系统
  • 原文地址:https://www.cnblogs.com/chucklu/p/14212061.html
Copyright © 2011-2022 走看看