Burst of Ice Burst of Ice - 3 months ago 13
JSON Question

Showing .net object from al class on a .cshtml page

I'm new to .NET and I'm trying to show my json on my .cshtml page and I don't know how to get it there. I also want to test what this class gives back since I don't know if it will work because I am getting the json from my localhost java ee backend. I am using an MVC template.

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; }
}
}


the .cshtml page looks like this

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


this is my 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"}]

Answer

Add a method to your 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};
    }

This is going to deserialize your json and re-serialize it in the JsonResult. This can be access with your path /home/TestJson.

If you just want to see the json string in the About view

    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();
    }

Then just call the ViewBag in the About view like this

<p>@ViewBag.Json</p>