ASP.NET MVC将JSON从控制器传递给View

tha*_*guy 5 asp.net asp.net-mvc json asp.net-mvc-4

想知道从API(以JSON格式)提取数据的最佳方法是什么.我的控制器中有代码,它调用返回数据的API.

我想将数据放到我的View上,这样我就可以在页面上显示它.我已经看到了使用jQuery/AJAX记录最多的方法,但我真的不希望将API网址公之于众.

我正在考虑传递从返回的数据创建的对象.但老实说,我不知道该怎么做!

以下代码返回每个用户的产品数据.这很好用.

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;
}
Run Code Online (Sandbox Code Playgroud)

目前我正在使用ViewBag将返回的数据传递给页面.如果有多个产品,这种方法效果不佳.我在ActionResult中传递了这个视图.

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;
}
Run Code Online (Sandbox Code Playgroud)

任何想法/例子将不胜感激.

Se0*_*g11 5

希望这能让你对它的实际工作方式有所了解

返回的一些示例作为actionresult来查看

调节器

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));
}
Run Code Online (Sandbox Code Playgroud)

视图

@model IEnumerable<productDetails>


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

JsonResult

一些返回json的例子来查看

调节器

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

用ajax打电话

$.post( "../something", {userGuid: "foo"}, function( data ) {
  console.log(data)
});
Run Code Online (Sandbox Code Playgroud)