5

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?

Hamid Reza
  • 2,913
  • 9
  • 49
  • 76

2 Answers2

6

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";
});
Eric Herlitz
  • 25,354
  • 27
  • 113
  • 157
  • I don't get why one would want a string of JSON and not a JS object literal .. also it seems like it (the JSON) would be invalid in the final HTML output? – user2864740 Feb 24 '14 at 08:42
  • @user2864740 I just need a json too fill hicharts category and series.highcharts.com. – Hamid Reza Feb 24 '14 at 08:53
2

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

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • Maybe I'm missing something .. why would someone want a *string* for "JSON-encoded" data? Wouldn't they want a JS object literal? Also it seems like it would just be *invalid* JS .. – user2864740 Feb 24 '14 at 08:41