ASP.NET MVC passing JSON to View from controller

31,083

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)
});
Share:
31,083
thatuxguy
Author by

thatuxguy

A forward thinking, fast learning, results driven professional specialising in Web Development, particularly ASP.NET and MS SQL development but equally capable of producing usable frontends utilising xHTML, HTML 5, CSS 2/3 and AJAX.

Updated on May 12, 2020

Comments

  • thatuxguy
    thatuxguy almost 4 years

    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.