javascript 在 jquery 的 razor 变量中设置值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25698574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:52:02  来源:igfitidea点击:

Set value in razor variable from jquery

javascriptjqueryasp.net-mvcrazor

提问by Manoj

I have a view in that I want to set value in razor variable from jQuery. I am trying like this

我有一个观点,我想在 jQuery 的 razor 变量中设置值。我正在尝试这样

@{
    ViewBag.Title = "Products";
    Layout = "~/Views/Shared/_Layout.cshtml";
    string ip_address = "";
}

<script type="text/javascript">
    $(function () {
        $.get("http://ipinfo.io", function (response) {
            console.log("ip+" + response.ip);
            '@ip_address' = response.ip;

        }, "jsonp");
    });
</script>

But this is throw an error Uncaught ReferenceError: Invalid left-hand side in assignment

但这是抛出错误 Uncaught ReferenceError: Invalid left-hand side in assignment

回答by pwdst

What you want to do is technically impossible - as has already been noted by the comments and the other answer.

你想要做的在技术上是不可能的 - 正如评论和其他答案已经指出的那样。

To summarise why this won't work, Razor is a view enginewhich uses C# code executed on the serverat the time of the page requestin order to build a HTML responsewhich is sent to the client.

总结一下为什么这不起作用,Razor 是一个视图引擎,它使用在页面请求时服务器上执行的 C# 代码来构建发送到客户端的 HTML响应

The client has no reference to the Razor variables, and the Razor view engine has no access to the JavaScript variables - although it could output JavaScript inside a script block which sets the initial value of the variable on page load.

客户端没有对 Razor 变量的引用,并且 Razor 视图引擎无法访问 JavaScript 变量 - 尽管它可以在脚本块中输出 JavaScript,该脚本块在页面加载时设置变量的初始值。

Even if JavaScript has got access to the Razor variables, it will only be executed when the page has been delivered to the user agent on the client device (browser in laymans terms), and it is much too latefor you to be doing any conditional rendering, showing/hiding of data or security checking at this point, or to use the variable within the view.

即使 JavaScript 可以访问 Razor 变量,它也只会在页面已交付给客户端设备(外行术语中的浏览器)上的用户代理时才会执行,而现在执行任何条件操作都为时已晚此时呈现、显示/隐藏数据或安全检查,或在视图中使用变量。

If you only want the client IP address then you already have access to this in the controller through the UserHostAddress propery of the Request object. Depending on what you want to do, you could pass this through the ViewBag from the controller to the view and render it ('Your IP address is...'), or if you are using it for security purposes use it within to the controller to filter the action returned to the view, or determine if the view should be rendered to the user at all (business/domain logic should generally not be carried out within the view itself).

如果您只需要客户端 IP 地址,那么您已经可以通过Request 对象UserHostAddress 属性在控制器中访问它。根据您要执行的操作,您可以通过 ViewBag 从控制器将其传递到视图并呈现它(“您的 IP 地址是...”),或者如果您出于安全目的使用它,则将其用于控制器过滤返回到视图的操作,或者确定是否应该将视图呈现给用户(业务/域逻辑通常不应在视图本身内执行)。

This also means that you are not reliant on a third-party service - your web server hasto know the IP address of the user requesting the page as it uses this to send the response back to their browser.

这也意味着您不依赖第三方服务 - 您的 Web 服务器必须知道请求页面的用户的 IP 地址,因为它使用它来将响应发送回他们的浏览器。

If you want other data that can only be determined from the browser, for example the size of the "viewport" (browser window) that the page is being rendered on - your best bet is to use a Ajax request to send this to a controller action as in No1_Melman's answer.

如果您想要其他只能从浏览器确定的数据,例如正在呈现页面的“视口”(浏览器窗口)的大小 - 最好的办法是使用 Ajax 请求将其发送到控制器动作如 No1_Melman 的回答。

回答by Callum Linington

I think I have just understood what you are trying to do.

我想我刚刚明白你想要做什么。

I strongly feel you don't know enough about ASP.NET yet to achieve what you want to do. So I highly recommend going through more tutorials on codeprojectand asp.netso that you can fully understand the MVC framework and how you use it.

我强烈认为您对 ASP.NET 的了解还不够,无法实现您想要做的事情。因此,我强烈建议您阅读更多关于codeprojectasp.net 的教程,以便您可以充分了解 MVC 框架以及如何使用它。

ORIGINAL RESPONSE

原始回复

You can post that information straight to you server if you want:

如果需要,您可以将该信息直接发布到您的服务器:

$(function () {
    $.get("http://ipinfo.io", function (response) {
        $.post("/MyController/Action", response);
    }, "jsonp");
}) 

Razor is only for rendering the output. So once you view the page in the browser it will have ZERO ties to razor, i.e. no interaction with it.

Razor 仅用于渲染输出。因此,一旦您在浏览器中查看该页面,它将与 razor 零关系,即与它没有交互。

My code doesn't load a partial, however, you can use JavaScript to render the UI once you've loaded the initial page (the one firing off the get to ipinfo). My code use jQuery to post the IP response to an action in MVC, so where mine says /MyController/Action, you replace with /Home/_ProductList. By the way you shouldn't really prefix an Action with "_"

我的代码不会加载部分代码,但是,一旦加载了初始页面(触发获取到 ipinfo 的页面),您就可以使用 JavaScript 来呈现 UI。我的代码使用 jQuery 将 IP 响应发布到 MVC 中的操作,所以我说的/MyController/Action,您替换为/Home/_ProductList. 顺便说一句,您不应该真正在 Action 前面加上“_”

So from what you are saying you want to load a partial, not an action, the comments confused me due to the code you were writing. Here is how I would do it:

因此,从您所说的要加载部分而不是动作的内容来看,由于您正在编写的代码,这些评论使我感到困惑。这是我将如何做到的:

@{
    ViewBag.Title = "Products";
    Layout = "~/Views/Shared/_Layout.cshtml";
    string ip_address = "";
}

@Html.Partial("_ProductList");

<script type="text/javascript">
    $(function () {
        $.get("http://ipinfo.io", function (response) {
            $.post("/MyController/Action", response.ip, function (successObj) {
                 // In here is where I set what ever in the partial

                 // I'm guessing that in the partial it renders some product table to view the products?
                 $.each(successObj, function (product) {

                    $("productTable").append(/* some new row using the product variable */);
                 });
             });            
               console.log("ip+" + response.ip);
        }, "jsonp");
    });
</script>