簡體   English   中英

ASP.NET MVC從控制器傳遞JSON到View

[英]ASP.NET MVC passing JSON to View from controller

想知道最好的方法是從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;
}

任何想法/例子將不勝感激。

希望這可以讓您對它的實際工作方式有所了解

返回作為操作結果查看的一些示例

控制者

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM