1

I'm calling a web API and the response is returned as an ContentResult.Content object. I retrieve this data in my asp.net MVC view and I'm trying to display this data in labels but I cant figure out how to parse this object into something i can work with.

Controller code:

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

View:

@using MVCApp.Controllers;

@{
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>
<p id="rData">
</p>
<div class="col-md-4">
</div>
</div>

@section scripts {
<script>

$(document).ready(function () {
    $.getJSON('/Home/getCall/', function (data) {
      // parse object here
    });
});
</script>
}
6
  • If you issue is that you cannot/ are unable to send data to the controller, why don't you use an Ajax call and JSON.Stringify? Commented Apr 23, 2019 at 9:13
  • It's not the best way to do it. I think it's better to perform this check in controller action, not in the view. ((HomeController)this.ViewContext.Controller).getCall(); is definitely wrong. Commented Apr 23, 2019 at 9:14
  • @RomanKoliada Yes, i deleted this code. I'll adjust this. Commented Apr 23, 2019 at 9:20
  • @JamesS I dont want to send data to the controller, im recieving data from the controller in ContentResult.Content object, I'm not sure how to parse this into something i can work it. Commented Apr 23, 2019 at 9:21
  • @JamesS, this code does work but returns a string and I can't fetch elements of my json response because its a string now. Commented Apr 23, 2019 at 9:30

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.