views:

66

answers:

2

I've been trying to figure out why this isn't valid (according to VS2008).

//Global variable
var sortFields;

$(document).ready(function() {
    sortFields = <%= CustomHtmlHelper.ToJson(ViewData["SortInfo"])%>;
    //Other Code here...
});

My HtmlHelper code

    public static string ToJson(object obj)
    {
        var serializer = new JavaScriptSerializer();
        var json = serializer.Serialize(obj);

        return json;
    }

The Helper is generating valid Json (confirmed it), but when I'm trying to add anything else to the function, VS2008 complains about all sort kinds of stuff, can't align the code correctly and so on when closing brackets, and as soon as I comment this out it works. However, the code works fine, even if VS2008 complains about it. Is this just VS2008 that is crap with JQuery or am I actually doing something wrong?

+3  A: 

The designer is generally going to get a bit upset when <%= is in script (and it sometimes gets snarly when it is in attribute values). If the output is correct, and you're happy with the way the html is constructed, then I wouldn't stress.

Ultimately, though; how does VS know that ToJson is going to return something sensible? It could return "(((((((" which would really screw up the javascript. That is why it is unhappy.

Marc Gravell
Okay I see. I'm just a bit annoyed with it because I'm quite new to JQuery and I use the auto allignment to confirm that I've done valid code, and all of a sudden, it's not doing that anymore. So that's why. Thanks for quick reply!
MrW
+2  A: 

MrW,

you,ve got a missing bracket here:

$(document).ready(function() {
    sortFields = <%= CustomHtmlHelper.ToJson(ViewData["SortInfo"])%>;
    //Other Code here...
};

it should be:

$(document).ready(function() {
    sortFields = '<%= CustomHtmlHelper.ToJson(ViewData["SortInfo"])%>';
    //Other Code here...
**)};**

also, it may be better to return a jsonresult?? Also, add single quotes around the CustomHtmlHelper as shown above.

jim
You're right about the **)};** but not the quotes. He wants an object literal here, not a string.
Duncan Smart
As Duncan sais, I want the object not a string. The last bracket was just typo now.
MrW
no worries, hope you've got it sorted for now..
jim
Yes, Thanks very much for quick replies! :)
MrW