0

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.

1
  • pass an object not an anonymous type Commented Nov 9, 2018 at 13:57

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you, but why >> Newtonsoft.Json.JsonConvert.SerializeObject ?!
@DinaDiagovic, var jsonData = @Html.Raw(Json.Encode(ViewBag.dataUnitsXX)) would also work, but MS now recommend using Json.NET rather than JavaScriptSerializer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.