Dina Diagovic
Dina Diagovic

Reputation: 701

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

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.

Upvotes: 0

Views: 429

Answers (1)

Sorin87bv
Sorin87bv

Reputation: 156

You can achieve this by adding the UnitsData list into the 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. Instead you are returning the model but adding the action result to the ViewBag. You may read more about action result types here.

Upvotes: 2

Related Questions