ASP.NET MVC传递JSON从控制器查看 [英] ASP.NET MVC passing JSON to View from controller

查看:128
本文介绍了ASP.NET MVC传递JSON从控制器查看的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在想,最好的办法是从一个API拉数据(JSON格式)。我有我的控制器,它调用返回数据的API code。

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.

我想要得到的数据到我的浏览这样我就可以在页面上显示它。我已经使用jQuery / AJAX见过的最有记录的方式,但我真的不想要的API网址的予以公开。

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!

下面code带回的产品数据,每个用户。这工作得很好。

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

而在present我使用ViewBag传递返回的数据页面。这不能很好地工作,如果有一个以上的产品。我传递这在为的ActionResult的看法。

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

任何想法/例子是多少AP preciated。

Any ideas/examples would be much appreciated.

推荐答案

希望这可以给你它是如何实际工作的一些想法

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

回报的ActionResult的一些例子来查看

Some example of return as actionresult to view

控制器

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

JsonResult

回报JSON的一些例子来查看

Some example of return as json to view

控制器

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

这篇关于ASP.NET MVC传递JSON从控制器查看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆