Set value in razor variable from jquery

I have a view that I want to set a value in a razor variable from jQuery. I try so hard

@{
    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 throws an error Uncaught ReferenceError: Invalid left-hand side in assignment

+3


source to share


2 answers


What you want to do is technically not possible - as noted in the comments and another answer.

To understand why this won't work, Razor is a view engine that uses C # code executed on the server at the time of a page request to construct an HTML response that is sent to the client .

The client has no reference to Razor variables, and the Razor viewer has no access to JavaScript variables - although it can output JavaScript inside a script block that initializes the variable on page load.

Even if JavaScript has access to Razor variables, it will only execute when the page is delivered to the user agent on the client device (browser in laymans terms) and it's too late for you to conditionally render, show / hide data, or validate security at this point or used a variable in the view.



If you only want the client's IP address, then you already have access to that in the controller through the UserHostAddress Property of the Request object . Depending on what you want to do, you can pass this through the ViewBag from the controller to the view and display it ("Your IP address ..."), or if you are using it for security purposes, use it inside the controller to filter the action returned to the view, or determine if the view should be displayed at all to the user (business / domain logic usually shouldn't run inside the view itself).

This also means that you are not relying on a third party service - your web server has to find out the IP address of the user requesting the page, as it uses this to send a response to their browser.

If you need other data that can only be determined in the browser, such as the size of the "viewport" (browser window) that the page is rendered on, your best bet is to use an Ajax request to send this to a controller action, as in # 1_Melman's answer.

+4


source


I think I just figured out what you are trying to do.

I strongly feel that you are not knowledgeable enough about ASP.NET, but to achieve what you want to do. Therefore, I highly recommend going through a few more tutorials on codeproject and asp.net so that you can fully understand the MVC framework and how you use it.

ORIGINAL ANSWER

You can send this information directly to your server if you want:

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

      



The razor is only for rendering the output. So as soon as you view the page in a browser it will have ZERO bindings to the razor i.e. No interaction with her.

My code doesn't load the partial, however you can use JavaScript to render the UI as soon as you have loaded the start page (one of which is disabled from ipinfo access). My code uses jQuery to post an IP response to an action in MVC, so when mine says /MyController/Action

, you replace with /Home/_ProductList

. By the way, you shouldn't prefix Action with "_"

So from what you say you want to load a partial and not an action, the comments are confusing me because of the code you were writing. This 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>

      

+1


source







All Articles