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?

2

2 Answers 2

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";
});
Sign up to request clarification or add additional context in comments.

2 Comments

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 I just need a json too fill hicharts category and series.highcharts.com.
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

1 Comment

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 ..

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.