thatuxguy
thatuxguy

Reputation: 2528

ASP.NET MVC passing JSON to View from controller

Was wondering what the best way is to pull data from an API (in JSON format). I have code in my controller, which calls an API which returns data.

I want to get the data onto my View so i can display it on a page. I have seen the most documented way by using jQuery/AJAX, but i dont really want the API url's to be made public.

I was thinking of passing an object created from the returned data. But in all honesty i am not sure how to do this!

The below code brings back the data for the products, per user. This works fine.

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 at present i am passing the returned data to the page using ViewBag. This does not work well if there is more than one product. I am passing this in the ActionResult for the view.

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

Any ideas/examples would be much appreciated.

Upvotes: 7

Views: 33810

Answers (1)

Se0ng11
Se0ng11

Reputation: 2333

Hope this can give you some idea on how it actually work

Some example of return as actionresult to view

Controller

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

View

@model IEnumerable<productDetails>


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

JsonResult

Some example of return as json to view

Controller

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

call with ajax

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

Upvotes: 6

Related Questions