2016-08-12 73 views
0

我正在使用SQL Server 2016在我的數據集中的字符串字段中返回json數據。我沒有任何轉換就將json字符串傳遞給模型。我想列舉我的JSON字符串場MVC剃刀一樣:如何在MVC Razor foreach循環中枚舉json字符串?

@foreach (var notification in Model.AccountSettings.EmailNotifications) 
{ 

EmailNotifications爲對象的JSON數組。

EmailNotifications = [{"EmailNotificationID":8,"EmailNotificationName":"Any new KLAS report is published.","IsSet":false},{"EmailNotificationID":9,"EmailNotificationName":"KLAS publishes a report in one of my areas of interest.","IsSet":false}] 

要做到這一點的最佳方法是什麼?

+0

我的猜測是,將不得不把對象作爲數組或東西。您可能還必須將每個項目投到其他項目。你爲什麼不想使用JSON.Net將其轉換爲對象? – Eonasdan

+0

因此,您有'Model.AccountSettings.EmailNotifications'中的'EmailNotification'類對象列表?或者它只是一個STRING?你的字符串值是怎樣的? – Shyju

+0

是的,它只是一個字符串 – Rodney

回答

2

乾淨的解決方案是創建一個類來表示您的JSON數組中的每個項目,將您的字符串轉換爲此類的列表並枚舉它。

public class NotificationItem 
{ 
    public int EmailNotificationID { get; set; } 
    public string EmailNotificationName { get; set; } 
    public bool IsSet { get; set; } 
} 

而且你可以使用Newtonsoft.Json.JsonConvert.DeserializeObject方法將JSON字符串列出NotificationItem對象的轉換。

@{ 
    var items = Newtonsoft.Json.JsonConvert 
       .DeserializeObject<List<NotificationItem>>("yourJsonStringHere"); 
} 
@foreach (var item in items) 
{ 
    <p>@item.EmailNotificationID</p> 
    <p>@item.EmailNotificationName </p> 
}