Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill javascript variables with c# ones?

I have these lines in my view.cshtml:

$("document").ready(function(){
    @{
        var cx = Json.Encode(ViewBag.x);
        var cy = Json.Encode(ViewBag.y);
    }
    var x = @cx;
    var y = @cy;
});

But now there is a red line under ; in javascript codes and the error is Syntax error.

What is the problem?

like image 939
Hamid Reza Avatar asked Feb 24 '14 08:02

Hamid Reza


2 Answers

You must enclose the js variables unless they are numeric or boolean

$("document").ready(function(){
    @{
        var cx = Json.Encode(ViewBag.x);
        var cy = Json.Encode(ViewBag.y);
    }
    var x = "@cx";
    var y = "@cy";
});
like image 111
Eric Herlitz Avatar answered Oct 27 '22 01:10

Eric Herlitz


Try to enclose the variables in "" like this:

$("document").ready(function(){
    @{
        var cx = Json.Encode(ViewBag.x);
        var cy = Json.Encode(ViewBag.y);
    }
    var x = "@cx";
    var y = "@cy";
});

You may also want to check ASP.NET MVC 3: Razor’s @: and syntax

like image 42
Rahul Tripathi Avatar answered Oct 26 '22 23:10

Rahul Tripathi