如何解析ASP.NET MVC视图中的JSON字符串

问题描述 投票:0回答:1

我在表中插入JSON字符串,而不是在foreach循环中的View中列出页面我想用Razor解析那个JSON字符串

@foreach (var item in Model) {
    var pr = JsonConvert.DeserializeObject<dynamic>(item.profile);
    //getting error 
    //the 'JsonConvert' does not exist in corrent context
    //and also the return type Profile was showing error so I changed it to `dynamic`
     <tr>
         <td>@pr.Name</td>
}
c# asp.net-mvc view json-deserialization
1个回答
0
投票

当您的应用程序变大时,您会觉得使用Model-View-Controller的标准方法会更好。当时可能难以重新编码您的应用程序。您可以使用此方法:

  1. 为JSON响应创建一个类。
  2. 创建一个Model类,其中包含JSON类作为属性,以及View所需的所有其他内容。
  3. 从Controller获取JSON,将其提供给Model,并将Model返回到View。
  4. 遍历视图中的模型(而不是JSON)。

如果您只是暂时测试某些内容,那么您可以在视图顶部添加@using Newtonsoft.Json,以使其识别JsonConvert.DeserializeObject方法。

© www.soinside.com 2019 - 2024. All rights reserved.