ASP.NET MVC passing JSON for viewing from the controller

I wonder how best to retrieve data from the API (in JSON format). I have code in a controller that calls an API that returns data.

I want to get data on my view so that I can display it on the page. I saw the most documented way using jQuery / AJAX, but I really don't want the API URL to be published.

I was thinking about passing an object created from the returned data. But to be honest, I'm not sure how to do this!

The code below returns data for products for each user. It works great.

public static List<productDetails> GetUserProducts(string userid)
{
    //api/product/user/<Guid>
    var url = baseUrl + "/product/user/" + userid;

    var syncClient = new WebClient();
    var content = syncClient.DownloadString(url);

    List<productDetails> Products = (List<productDetails>)Newtonsoft.Json.JsonConvert.DeserializeObject(content, typeof(List<productDetails>));

    return Products;
}

And currently I am passing the returned data to the page using the ViewBag. This does not work if there is more than one product. I pass this to ActionResult for presentation.

var p = GetUserProducts(userGuid);

foreach(var product in p)
{
    ViewBag.pId = product.Id;
    ViewBag.pName = product.FriendlyName;
    ViewBag.pSerial = product.SerialNumber;
    ViewBag.pbatt = product.Location.BatteryCharge + "%";

    ViewBag.devicehistory = "~/Location/History/" + product.Id;
}

/ .

+4
1

, ,

public ActionResult something(string userGuid)
{
    var p = GetUserProducts(userGuid);
    return view(p); //you can return as partial view  (return PartialView("your partial view name", p));
}

@model IEnumerable<productDetails>


 foreach (var item in Model)
{
   @Html.DisplayFor(model => item.Id)
   //and so on
}

JsonResult

json

   [httpPost]
    public JsonResult something(string userGuid)
    {
        var p = GetUserProducts(userGuid);
        return Json(p, JsonRequestBehavior.AllowGet);
    }

ajax

$.post( "../something", {userGuid: "foo"}, function( data ) {
  console.log(data)
});
+5

Source: https://habr.com/ru/post/1540199/


All Articles