3

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

3
  • 1
    Thats not the idea of razor, razor renders the UI output. Javascript manipulates the UI and then the page posts the information back to the server. I suggest you read up more on asp.net Commented Sep 6, 2014 at 8:58
  • 1
    Razor is server side code. string ip_address no longer exists once its sent to the browser so you cant set it using javascript which runs on the client. Commented Sep 6, 2014 at 9:01
  • It is not possible, Razor execute on server side, and jquery execute on client side. Commented Sep 6, 2014 at 9:04

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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, i.e. 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>

4 Comments

I want to use this ip_address for calling partial view like this @Html.Action("_ProductList", "Home", new { ip = ip_address })
That is what my code does. My code use jQuery to post 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 "_"
We use "_" only for partial views.
Ahh, see I got confused because your code says "Action", not "Partial". In short, you can't do what you want to do that way. The way I achieve what you do is to render the partial in the main view, then I set it up with jQuery or actual Knockout

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.