MVC Json to HTML table

本文关键字:table HTML to Json MVC | 更新日期: 2023-09-27 17:55:05

我试图将序列化的json字符串(使用JsonConvert.SerializeObject序列化)传递到html表。我想调用json字符串中的值到表中,像这样:"model.jsonvalue"。我不确定如何使json字符串的变量。

My Json string:

{
  "stats": {
    "global": {
      "cache": {
        "misses": "5"
      },
      "download": {
        "total-downloaded": "500"
      },
      "error": {
        "config-failed": "50",
        "retries": "20"
      },
      "instance": {
        "resets": "2016-06-23 09:45:07"
      },
      "servers": {
        "server-in-config": "1",
        "servers-running": "1",
        "servers-relays": "1"
      }
    },
    "servers": {
      "12345": {
        "uptime": "0d, 18:01:30",
        "retries": "0",
        "download-size": "54664",
        "server-restart": "1",
        "download-time": "1",
        "start-time": "2016-06-23 09:45:07",
        "logic-time": "123",
        "heartbeat": "1",
        "logic-retry": "0"
      },
      "44444": {
        "start-time": "2016-06-23 09:45:07",
        "download-time": "1",
        "logic-time": "123",
        "download-size": "54664",
        "server-restart": "1",
        "logic-retry": "0",
        "uptime": "0d, 18:01:30",
        "heartbeat": "1",
        "retries": "0"
      }
    }
  }
}

在我的控制器中,我序列化如下:

string json = System.IO.File.ReadAllText(@path);
string jsonoutput = JsonConvert.SerializeObject(json);

…我有一个控制器,用于我想传递给表的值,如下所示:

public class Stats
{
    public Global global { get; set; }
    public List<server> servers { get; set; }
}
public class Global
{
    public Cache cache { get; set; }
    public Download download { get; set; }
    public Error error { get; set; }
    public Instance instance { get; set; }
    public servers servers { get; set; }
}

现在我知道有很多文章解释如何做到这一点(我做了谷歌),但我不想使用ajax, javascript, knockout或任何脚本。就是普通的MVC。

希望有人可以帮助,因为我是非常新的MVC和json。

MVC Json to HTML table

如果你只想要普通的ASP MVC,那么不要将数据从file转换为json。将它加载到你的静态类型模型(全局类),然后将它从控制器传递给视图,即:

控制器' DataController.cs:

public class DataController : Controller
{
    public ActionResult Index()
    {
        string data = System.IO.File.ReadAllText(@path);
        var model = ConvertDataToModelSomehow(data); //model variable type: Global 
        return View(model);
    }
}

然后你可以使视图和使用你的模型- Views'Data'Index.cshtml:

@model Global //your model type passed to view
<table>
    <thead>
        <tr>
            <th>Server name</th>
        </tr>
    </thead>
    <tbody>
    @foreach(var item in Model.servers) //if Global.servers will be collection
    {
        <tr>
            <td>@item.Name</td> //if element has Name property
        </tr>
    }        
    </tbody>
</table>

更多信息在这里