0

I am using JQWidgets and I am trying to serialize my model to JSON before using the JSON to populate a JQWidgets table. However I get this error:

Uncaught SyntaxError: Unexpected token i 

I think that my JSON is invalid because of how I serialize my model object by mixing RAZOR with javaScript/jQuery. This is the rest of my code:


public ActionResult _NewsWidget()
        {

            var v = JArray.Parse(JsonConvert.SerializeObject(news.GetNewsItems(), formatting: Formatting.Indented));
            var model = (from p in v
                                select new ModelNewsWidget()
                                {
                                    Id = p["UniqueId"].ToString(),
                                    ImagePath = "<a onclick=\"initSingleNews(" + p["UniqueId"] + ")\" href=\"javasscript:void(0)\">" +
                                    "<img style=\"width: 100px;\" alt=\"\" src=\"" + _imagePath + p["NewsItemImageReference"] + "\"></img>" +
                                    "</a>",
                                    BodyText = 
                                    "<b>" + p["Title"] + "</b></br></br>" +
                                    "<b>" + p["AddedOn"].ToString().Substring(0, 10) + "</b></br>" +
                                    p["BodyTextFormatted"].ToString().Substring(0, 18) + "</br></br>" +
                                    p["BodyText"].ToString().Substring(18, 100).Insert(100, "...<a class=\"newsMore\" href=\"#\" onclick=\"initSingleNews(" + p["UniqueId"] + ")\" >More</a>")
                                }).ToList();

            ViewBag.StartupScript = "initNewsWidget();";
            return View("~/PartialViews/News/_NewsWidget.cshtml", model);
        }

Partial View

@model List<AMT2014_Prototype.Models.News.ModelNewsWidget>

<script>

    function _createWindow() {
        $("#jqxwindow-news").jqxWindow({ width: 720, height: 600, autoOpen: false, draggable: true });
    };

    function bindNewsTable(data) {
        var source =
        {
            dataType: "json",
            dataFields: [
                { name: 'id', type: 'int' },
                { name: 'imagePath', type: 'string' },
                { name: 'title', type: 'string' },
                { name: 'text', type: 'string' }
            ],
            localData: data,
        };
        var dataAdapter = new $.jqx.dataAdapter(source);

        $("#newsTable").jqxDataTable(
        {
            source: dataAdapter,
            showHeader: false,
            autoRowHeight: false,
            width: '100%',
            columns: [
                { text: 'Image', dataField: 'imagePath', width: 120 },
                { text: 'Body Text', dataField: 'text', width: 320 }
            ]
        });
    }

function initNewsWidget() {
    var json = '@Html.Raw(Json.Encode(Model))';
    console.log(json);
    bindNewsTable(json);
}

<div id='jqxWidget' caption="News" style="height: 400px; width: 600px;">
    <div id="newsTable">
    </div>
</div>

<div id='jqxwindow-news' style=" overflow: scroll;">
    <div>Details</div>
    <div id="newsDetailsTable" style="padding: 10px;">
    </div>
</div>

<script type="text/javascript" defer="defer">
    @Html.Raw(ViewBag.StartupScript)
</script>

JSON LINT

[
    {
        "Id": "6",
        "ImagePath": "<a onclick="initSingleNews(6)" href="javasscript: void(0)"><img style="width: 100px;" alt="" src="9750cf57-bc14-4205-9e6c-83c8406f3f82.jpg"></img></a>",
        "BodyText": "<b>Tree fungus ID: Inonotus dryadeus</b></br></br><b>16/09/2013</b></br>Ref: 204201/252874</br></br>
The fruiting bodies are those of a fungus called Inonotus dryadeus. Oak is the most common host of...<a class="newsMore" href="#" onclick="initSingleNews(6)" >More</a>"
    }
]ick="initSingleNews(6)">More</a>"
    }
]


Results

Parse error on line 4:
...Path": "<a onclick="initSingleNews(6)" h
-----------------------^
Expecting '}', ':', ',', ']'
  1. Should I return JSON from my controller instead? I had problems with encoding before which is why I am trying to encode my model in my view.
  2. Why is my JSON invalid in Lint?
3
  • verify your json first try Http://jsonformatter.curiousconcept.com this link to verify if your JSON is valid or not Commented Oct 28, 2014 at 11:46
  • @DotNetIsMyPower I used your link and it's complaining about the use of colons in the JSON. I was originally serializing my JSON in my controller but the encoding was giving me problems. Commented Oct 28, 2014 at 11:52
  • that means your JSON is invalid, can you please post your JSON string here? Commented Oct 28, 2014 at 12:52

3 Answers 3

1

Your JSON is invalid:

[
    {
        "Id": "6",
        "ImagePath": "<a onclick="initSingleNews(6)" href="javasscript: void(0)"><img style="width: 100px;" alt="" src="9750cf57-bc14-4205-9e6c-83c8406f3f82.jpg"></img></a>",
        "BodyText": "<b>Tree fungus ID: Inonotus dryadeus</b></br></br><b>16/09/2013</b></br>Ref: 204201/252874</br></br>The fruiting bodies are those of a fungus called Inonotus dryadeus. Oak is the most common host of...<a class="newsMore" href="#" onclick="initSingleNews(6)" >More</a>"
    }
]

It should look like:

[
    {
        "Id": "6",
        "ImagePath": "<a onclick=\"initSingleNews(6)\" href=\"javasscript: void(0)\"><img style=\"width: 100px;\" alt=\"\" src=\"9750cf57-bc14-4205-9e6c-83c8406f3f82.jpg\"></img></a>",
        "BodyText": "<b>Tree fungus ID: Inonotus dryadeus</b></br></br><b>16/09/2013</b></br>Ref: 204201/252874</br></br>The fruiting bodies are those of a fungus called Inonotus dryadeus. Oak is the most common host of...<a class=\"newsMore\" href=\"#\" onclick=\"initSingleNews(6)\" >More</a>"
    }
]

All double quotes should be escaped. This could be done through JavaScriptSerializer.Serialize Method (Object)

Something like this:

var json = @Html.Raw((new JavaScriptSerializer()).Serialize(Model));

Sign up to request clarification or add additional context in comments.

Comments

1
  1. Should I return JSON from my controller instead? I had problems with encoding before which is why I am trying to encode my model in my view.

It is fine to do that in view but still not a convinced way of doing that still it'll work.

  1. Why is my JSON invalid in Lint?

It's because your generated hyperlink in the ImagePath and BodyText property of your json data has multiple double quotes (") which is should be single quotes (') for the attribute values.

My suggestion is to use the Json serializer (using Newtonsoft) to serialize the model to get in json format.

var json = '@Html.Raw(JsonConvert.SerializeObject(model))';

namespace: using Newtonsoft.Json;

2 Comments

I tried using Newtonsoft and when I call bindNewsTable(json); I get an error about Uncaught SyntaxError: Unexpected token i
Can you show me the generated json data and what does the bindNewsTable function does?
0

Your JSON string is invalid

try this one

[
    {
        "Id": "6",
        "ImagePath": "<a onclick='initSingleNews(6)' href='javasscript: void(0)'><img style='width: 100px;' alt='' src='9750cf57-bc14-4205-9e6c-83c8406f3f82.jpg'></img></a>",
        "BodyText": "<b>Tree fungus ID: Inonotus dryadeus</b></br></br><b>16/09/2013</b></br>Ref: 204201/252874</br></br>The fruiting bodies are those of a fungus called Inonotus dryadeus. Oak is the most common host of...<a class='newsMore' href='#' onclick='initSingleNews(6)' >More</a>"
    }
]

Comments

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.