ASP.NET MVC控制器将JSON传递给视图

7

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

我想要将数据传输到我的视图上,以便在页面上显示它。我看到了使用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;
}

目前我正在使用 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;
}

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

为什么不直接使用“Model”而不是“ViewBag”呢? - cem
我已经设置了一个模型,说实话,我对MVC还是很新的。你有例子吗? - thatuxguy
1个回答

6
希望这可以给您一些关于它如何工作的想法。
将一些返回值作为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));
}

查看

@model IEnumerable<productDetails>


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

JsonResult(返回JSON结果)

以下是将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)
});

1
第一部分非常有效,正是我所需要的,我想:D干杯! - thatuxguy
如果我有第二个 - 例如 var p2 = GetUserOtherProducts(userGuid); 怎么办?我该如何将其传递给视图?这是否需要使用部分视图? - thatuxguy
1
如果两者是完全不同的模型(应该是不同的模型),那么你需要创建一个“ViewModel”,你可以参考这个链接https://dev59.com/NGQn5IYBdhLWcg3wzZ76获取更多信息。 - Se0ng11
感谢您的帮助!:D 以下是相关编程内容的翻译:使用此链接 - https://dev59.com/hGw05IYBdhLWcg3w72M0 - thatuxguy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接