Search code examples
c#jqueryasp.net-mvclistviewbag

How to retrieve data from view bag in jquery(inside the view) in c#, mvc


I'm sending a List using ViewBag to the view like this.

List<RegionSearch> rs = searchregionArray.Select(sr => new RegionSearch()
{
    region = (string)sr["AREA/DEST"],

}).ToList();

var filteredRegion = rs.Select(k => k.region).Distinct();

//testing 
ViewBag.checking = rs;

now I want to get it in <script></script> .how can I do that


Solution

  • Try this :-

    <script>
       var jsonList = '@Html.Raw(Json.Convert(ViewBag.checking))'
       var jsList = JSON.parse(jsonList);
       console.log(jsList);
    </script>
    

    NOTE :- Although not a good idea sending whole list from controller to view inside ViewBag instead use ViewModel.