Tom Gillard
Tom Gillard

Reputation: 575

Invalid property ID error - JSON object from List<> c# ASP.NET

I've been on this for a couple of days now and getting nowhere.

I'm trying to serialize a List object to JSON so it can be passed to Google Analytics' e-commerce service, so it needs to get passed into javascript beforehand.

However, there is an error with the json output.

First of all I have an Item class.

Item {
    Id,
    Name,
    Sku,
    Price,
    Quantity
}

My cart class contains a List of Items

public List<Item> Items;

I'm using the following to serialize the list.

var jsonList = JavascriptSerializer.Serialize(cart.Items);

jsonList is then passed into javascript using Razor like so -

<script type="text/javascript">
    var items = @jsonList;
</script>

The result that is generated in the browser looks like this:

items = [{&quot;Id&quot;:ITEM_ID,&quot;Name&quot;:&quot;ITEM_NAME&quot;,&quot;Sku&quot;:&quot;ITEM_SKU&quot;,&quot;Quantity&quot;:ITEM_QTY,&quot;Price&quot;:ITEM_PRICE},{&quot;Id&quot;:ITEM2_ID,&quot;Name&quot;:&quot;ITEM2_NAME&quot;,etc...}]

So I'd like to know how I get rid of the &quot and replace them with the required " instead. Does it have something to do with my Item class or my javascript?

I've tried @Html.Raw(items) and no luck - returns an empty json object.

Upvotes: 1

Views: 2198

Answers (2)

Tom Gillard
Tom Gillard

Reputation: 575

Found a solution that worked on the following post.

How do I write unencoded Json to my View using Razor?

Thanks to @James for mentioning unencoded HTML - that put me on the right path.

Upvotes: 1

James
James

Reputation: 82136

You could use Html.Raw to return unencoded HTML

var items = @Html.Raw(@jsonList);

Upvotes: 5

Related Questions