在.cshtml页面上显示来自al class的.net对象

时间:2016-08-24 13:42:58

标签: .net json asp.net-mvc razor

我是.NET的新手,我试图在我的.cshtml页面上展示我的json而且我不知道如何在那里找到它。我也想测试这个类给出的内容,因为我不知道它是否会起作用,因为我从我的localhost java ee后端获取了json。我正在使用MVC模板。

class Evaluatie
{
    static void Main(string[] args)
    {
        var client = new WebClient();
        var response = client.DownloadString(new Uri("http://localhost:8080/projecten/api/leerlingen"));

        var j = JsonConvert.DeserializeObject<Leerling>(response);
    }

    public class Leerling
    {
        public string inschrijvingsNummer { get; set; }
        public string naam { get; set; }
        public string email { get; set; }
        public string evaluatieNummer { get; set; }
    }
}

.cshtml页面如下所示

@{
    ViewBag.Title = "Evaluaties";
}
<h2>@ViewBag.Title.</h2>

这是我的json:

[{"inschrijvingsNummer":"0001","naam":"Joske Vermeulen","email":"joske.vermeulen@hotmail.be","evaluatieNummer":"270"},
{"inschrijvingsNummer":"0002","naam":"Kamiel Spiesses","email":"Kamiel.spiesses@gmail.com","evaluatieNummer":"370"}]

1 个答案:

答案 0 :(得分:2)

向HomeController添加方法。

    public JsonResult TestJson()
    {
        var client = new WebClient();
        var response = client.DownloadString(new Uri("http://localhost:8080/projecten/api/leerlingen"));

        var someObject = JsonConvert.DeserializeObject<List<Leerling>>(response);

        return new JsonResult() {Data = someObject, JsonRequestBehavior = JsonRequestBehavior.AllowGet};
    }

这将反序列化你的json并在JsonResult中重新序列化它。这可以通过您的路径/ home / TestJson访问。

如果您只想在“关于视图”中查看json字符串

    public ActionResult About()
    {
        ViewBag.Message = "Your application description page.";

        var client = new WebClient();
        ViewBag.Json = client.DownloadString(new Uri("http://localhost:8080/projecten/api/leerlingen"));

        return View();
    }

然后只需在此关键视图中调用ViewBag

<p>@ViewBag.Json</p>