Asp.net-Mvc
將 IQueryable 泛型轉換為 JSON
我正在通過以下方式製作投影:
var query = from book in books select new { label = book.Title, value = book.ID };在我的剃須刀頁面中,我需要使用:
var booksArray = [{ @(json) }];這樣生成的數組看起來像:
label: 'c++', value: 'c++' }, { label: 'java', value: 'java' }, { label: 'php', value: 'php' }, { label: 'coldfusion', value: 'coldfusion' }我已經從幾種不同的方法中非常接近了——我可以得到一個在伺服器端看起來正確的字元串,但是當呈現到頁面本身時,所有
'標記都變為'.但專注於通過 JSON.net 實現這一目標……
最可能的方法似乎應該是:
var json = JsonConvert.ToString(query);但這折騰:
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.什麼是正確的 JSON.net 語法?
謝謝
ToArray()評估查詢並使JsonConvert快樂var query = from book in books select new { label = book.Title, value = book.ID }; var json = JsonConvert.SerializeObject(query.ToArray());注意:
JsonConvert.SerializeObject如果要序列化複雜類型,則需要使用。JsonConvert.ToString用於轉換簡單類型,如 bool、guid、int、uri 等。在您看來
Html.Raw,不要對 JSON 進行 html 編碼:var booksArray = @(Html.Raw(json))