Reputation: 386
I am using the MVC template from .net and I can show my json but now i want to parse it to html, preferrably in a table, so it looks better.
I get the json from my HomeController.cs to my View which is About.cshtml but it's just the json string, so it looks horrible.
public class HomeController : Controller
{
public JsonResult TestJson()
{
var client = new WebClient();
var response = client.DownloadString(new Uri("http://localhost:8080/projecten/api/leerlingen"));
var someObject = JsonConvert.DeserializeObject(response);
return new JsonResult() { Data = someObject, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
public ActionResult About()
{
var client = new WebClient();
var json = client.DownloadString(new Uri("http://localhost:8080/projecten/api/leerlingen"));
//parse json
ViewBag.Message = json;
return View();
}
}
this it the json
[{"inschrijvingsNummer":"0001","naam":"John Smith","email":"[email protected]","evaluatieNummer":"270"},
{"inschrijvingsNummer":"0002","naam":"Joe Bloggs","email":"[email protected]","evaluatieNummer":"370"}]
to html with .net i show it in this page (About.cshtml)
@{
ViewBag.Title = "Evaluaties";
}
<h2>@ViewBag.Title.</h2>
<p>@ViewBag.Message</p>
Upvotes: 3
Views: 17652
Reputation: 218722
You should basically create a class which represent the data in your json array.
public class FancyPerson
{
public string InschrijvingsNummer { get; set; }
public string Naam { get; set; }
public string Email { get; set; }
public string EvaluatieNummer { get; set; }
}
and when you get the json string (which contains an array of items) from your http call, de-serialize it to a collection of this class.
var items = Newtonsoft.Json.JsonConvert.DeserializeObject<IEnumerable<FancyPerson>>(json);
ViewBag.Message = items;
Now in your view, you just need to cast this ViewBag item to List of FancyPerson
object's. You can loop through the items and show it in table rows.
@{
var items = (List<FancyPerson>) ViewBag.Message;
}
<table>
@foreach (var item in items)
{
<tr>
<td>@item.Naam</td>
<td>@item.Email</td>
</tr>
}
</table>
Upvotes: 1