How to display JSON response into MVC view without predefining JSON structure?

  • Thread starter Thread starter Niels Schutte
  • Start date Start date
N

Niels Schutte

Guest
I'm creating a MVC ASP.NET frontend where I am trying to display the json response of any API endpoint without predefining their structure.

I'm trying to achieve that theJSON response from my Web API is being displayed with labels and with their values.

HomeController:

[HttpGet]
public async Task<ActionResult> getCall()
{
string url = "http://localhost:51080/";
string customerApi = "customer/1";

using (var client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage response = await client.GetAsync(customerApi);
if (response.IsSuccessStatusCode)
{
string jsondata = await response.Content.ReadAsStringAsync();
return Content(jsondata, "application/json");
}
return Json(1, JsonRequestBehavior.AllowGet);
}
}

Json reponse of this method:

{"$id":"1","PropertyLeaseContracts":[{"$id":"2","Customer":{"$ref":"1"},"LeaseContract":{"$id":"3","PropertyLeaseContracts":[{"$ref":"2"}],"leaseContractID":1,"leaseDurationMonths":12,"leaseMonthlyCosts":500.0},"Property":{"$id":"4","PropertyLeaseContracts":[{"$ref":"2"}],
"propertyID":1,"propertyName":"Saints Castle","propertyLocation":"Emmen","propertyType":"Castle","propertyOwner":"Saint Martin"},"propertyLeaseContractID":1,"leaseContractID":1,"propertyID":1,"customerID":1}],"customerID":1,"customerFirstName":"Jan","customerLastName":"Wubs","customerGender":"Male"}

Home/Index.cshtml View:

@{
ViewBag.Title = "Dashboard";
if (Session["userID"] == null)
{
Response.Redirect("~/Login/Index");
}
}

<div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
<p>
<!-- Labels with values here! -->
</p>
</div>
<div class="col-md-4">
</div>
<div class="col-md-4">
</div>


Hope somebody got a solution for me!

Thanks!





Continue reading...
 

Similar threads

Back
Top