RedAces
RedAces

Reputation: 317

Scope of global variables in MVC View

When I use global JavaScript variables in a View of MVC with Ajax, would the global variable be reset (re-declared) even though the page isn't refreshed?

i.e.

<script>
var global = 0;
function func()
{
     global = 2;

     //passing global variable to a method "int square(int number)" in Home Controller
      $.ajax(
        {
            type: "POST",
            url: "../Home/square",
            data: { number : global },
            success: function (result)
            {
                alert(result);
            }
         };
}
</script>

Generally, what events would cause global variables in JavaScript to reset?

Upvotes: 0

Views: 959

Answers (1)

ProxyTech
ProxyTech

Reputation: 1145

Global variables in JavaScript will only be reinitialized in the event of a page refresh (i.e. F5 in your browser).

The page could be declared as a partial view and brought in via Ajax in which case the "Parent" page might not be refreshed, but each ajax request for the partial view would cause the JavaScript variables of that view to be re-initialized. Barring this scenario, your original statement about JavaScript variables and their lifetime would be correct.

Upvotes: 1

Related Questions