I’m producing a projection via:
var query = from book in books
select new
{
label = book.Title,
value = book.ID
};
In my razor page I need to use:
var booksArray = [{
@(json)
}];
such that the resulting array looks like:
label: 'c++',
value: 'c++'
}, {
label: 'java',
value: 'java'
}, {
label: 'php',
value: 'php'
}, {
label: 'coldfusion',
value: 'coldfusion'
}
I’ve come very very close from a couple different approaches – I can get a string that looks correct on the server side but when rendered to the page itself, all the ' marks become ' .
But focusing on achieving this via JSON.net…
The most likely approach seems like it should be:
var json = JsonConvert.ToString(query);
but that tosses:
Unsupported type: System.Linq.Enumerable+WhereSelectListIterator`2[Project.Entity.Book,<>f__AnonymousType3`2[System.String,System.Int32]]. Use the JsonSerializer class to get the object's JSON representation.
What’s the correct JSON.net syntax?
thx
You need a combination of .ToArray() and Html.Raw()
ToArray()to evaluate the query and makeJsonConverthappyNote: you need to use
JsonConvert.SerializeObjectif you want to serialize complex types.JsonConvert.ToStringis used to convert simple types like bool, guid, int, uri etc.And in your view
Html.Rawto not html encode the JSON: