How to set javascript variables using MVC4 with Razor

Solution 1:

You should take a look at the output that your razor page is resulting. Actually, you need to know what is executed by server-side and client-side. Try this:

@{
    int proID = 123; 
    int nonProID = 456;
}

<script>

    var nonID = @nonProID;
    var proID = @proID;
    window.nonID = @nonProID;
    window.proID = @proID;

</script>

The output should be like this:

enter image description here

Depending what version of Visual Studio you are using, it point some highlights in the design-time for views with razor.

Solution 2:

Since razor syntax errors can become problematic while you're working on the view, I totally get why you'd want to avoid them. Here's a couple other options.

<script type="text/javascript">
    // @Model.Count is an int
    var count = '@Model.Count';
    var countInt = parseInt('@Model.ActiveLocsCount');
</script>

The quotes act as delimiters, so the razor parser is happy. But of course your C# int becomes a JS string in the first statement. For purists, the second option might be better.

If somebody has a better way of doing this without the razor syntax errors, in particular maintaining the type of the var, I'd love to see it!

Solution 3:

This is how I solved the problem:

@{int proID = 123; int nonProID = 456;}

<script type="text/javascript">
var nonID = Number(@nonProID);
var proID = Number(@proID);
</script>

It is self-documenting and it doesn't involve conversion to and from text.


Note: be careful to use the Number() function not create new Number() objects - as the exactly equals operator may behave in a non-obvious way:

var y = new Number(123); // Note incorrect usage of "new"
var x = new Number(123);
alert(y === 123); // displays false
alert(x == y); // displays false