简体   繁体   English

从jquery设置razor变量中的值

[英]Set value in razor variable from jquery

I have a view in that I want to set value in razor variable from jQuery. 我有一个观点,我想从jQuery中设置razor变量的值。 I am trying like this 我这样想

@{
    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

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 engine which uses C# code executed on the server at the time of the page request in order to build a HTML response which 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 late for 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 . 如果您只需要客户端IP地址,那么您已经可以通过Request对象UserHostAddress属性在控制器中访问它。 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). 根据您的想法,您可以通过ViewBag将其从控制器传递到视图并呈现它('您的IP地址是......'),或者如果您出于安全目的使用它,请将其用于控制器过滤返回到视图的操作,或者确定是否应该向用户呈现视图(通常不应在视图本身内执行业务/域逻辑)。

This also means that you are not reliant on a third-party service - your web server has to 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的回答一样。

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. 我强烈认为你对ASP.NET的了解还不够,无法实现你想做的事情。 So I highly recommend going through more tutorials on codeproject and asp.net so that you can fully understand the MVC framework and how you use it. 因此,我强烈建议您阅读有关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. Razor仅用于渲染输出。 So once you view the page in the browser it will have ZERO ties to razor, ie no interaction with it. 因此,一旦您在浏览器中查看该页面,它将与剃刀具有ZERO关系,即不与其进行交互。

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). 我的代码没有加载部分,但是,一旦你加载了初始页面(触发到ipinfo的那个),你可以使用JavaScript来呈现UI。 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 . 我的代码使用jQuery将IP响应发布到MVC中的一个动作,所以在我的/MyController/Action ,你用/Home/_ProductList替换。 By the way you shouldn't really prefix an Action with "_" 顺便说一下,你不应该用“_”为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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM