简体   繁体   中英

Set value in razor variable from jquery

I have a view in that I want to set value in razor variable from jQuery. 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

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 .

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.

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.

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

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.

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.

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 codeproject and asp.net so that you can fully understand the MVC framework and how you use it.

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, ie no interaction with it.

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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