2016-07-04 80 views
0

我想通过一个序列化的JSON字符串(使用JsonConvert.SerializeObject序列化)到一个HTML表。我想将json字符串中的值调用到表中,如下所示:“model.jsonvalue”。我不知道如何从json字符串中创建变量。MVC Json到HTML表

我的JSON字符串:

{ 
    "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" 
     } 
    } 
    } 
} 

在我的控制器I序列如下:

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,淘汰赛或任何脚本。只是简单的MVC。

希望有人可以提供帮助,因为我对MVC和json非常陌生。

+0

我不认为你可以有MVC没有JavaScript,而据我所知,使用JSON工作的唯一明智的方法是使用AJ斧头。 Knockout实际上是MVVC,与MVC略有不同。 – TW80000

+1

如果你不想使用JavaScript,那么使用JSON就没有太多的意义。如果您只想使用MVC视图,那么使用剃须刀编写一个循环,直接将模型中的项目转换为HTML表格中的行。 – ADyson

回答

1

如果你只想要简单的ASP MVC,那么不要将数据从文件转换为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); 
    } 
} 

然后你就可以查看和使用模型 - 视图\ 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> 

More info here