简体   繁体   English

C#-MVC-JSON-使用ViewBag从服务器端到客户端返回列表

[英]C# - MVC - JSON - Return List From Server Side to Client Side Using ViewBag

Hello everyone, 大家好,

i'm need to return list to client side using viewbag and return view 我需要使用Viewbag将列表返回到客户端并返回视图

let's see code : 让我们看一下代码:

Server Side : 服务器端 :

var model = _iSiteService.FindProduct(id);
    var UnitsData = _iSiteService.GetAllProductsUnits(id).Where(x => x.Product.IsActive).Select(i => new
                        {
                            i.Id,
                            i.UnitId,
                            i.ConversionFactor,
                            i.ProductId
                        }).ToArray();

                        ViewBag.dataUnitsXX = Json(new
                        {
                            Data = UnitsData.ToArray()
                        }, JsonRequestBehavior.AllowGet);

    return View(model);

Client Side : 客户端 :

var json = @Html.Raw(ViewBag.dataUnitsXX);

Message Error : 讯息错误:

var json = System.Collections.Generic.List`1[<>f__AnonymousType2`4[System.Int32,System.Int32,System.Decimal,System.Int32]];

How i can solved it. 我该如何解决。

please help me to return data in variable in javascript Thanks You. 请帮助我以javascript中的变量形式返回数据谢谢。

You can achieve this by adding the UnitsData list into the ViewBag: 您可以通过将UnitsData列表添加到ViewBag中来实现:

 ViewBag.dataUnitsXX = UnitsData;

and then client side using: 然后客户端使用:

var jsonData = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.dataUnitsXX));

Please note that the way you try to serialize data is a mix of concepts. 请注意,您尝试序列化数据的方式是多种概念的组合。 The Json you are using there is meant to return an action result of type json. 您在此处使用的Json旨在返回json类型的操作结果。 Instead you are returning the model but adding the action result to the ViewBag. 相反,您将返回模型,但会将操作结果添加到ViewBag。 You may read more about action result types here . 您可以在此处阅读有关操作结果类型的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM