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 make JsonConvert
happy
var query = from book in books
select new
{
label = book.Title,
value = book.ID
};
var json = JsonConvert.SerializeObject(query.ToArray());
Note: you need to use JsonConvert.SerializeObject
if you want to serialize complex types. JsonConvert.ToString
is used to convert simple types like bool, guid, int, uri etc.
And in your view Html.Raw
to not html encode the JSON:
var booksArray = @(Html.Raw(json))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With