nick gowdy
nick gowdy

Reputation: 6511

Serializing MVC model to JSON in view - Uncaught SyntaxError: Unexpected token i

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?

Upvotes: 0

Views: 2625

Answers (3)

Venkatesh
Venkatesh

Reputation: 1224

  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;

Upvotes: 1

Mox Shah
Mox Shah

Reputation: 3015

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>"
    }
]

Upvotes: 0

webdeveloper
webdeveloper

Reputation: 17288

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));

Upvotes: 1

Related Questions