Search code examples
jqueryasp.net-mvcviewbag

How to read ViewBag list in jquery


I have a list that I want to pass from my Controller to my View and use JQuery to loop through the list. In my jquery, I can see the ViewBag object but how do I expand the data to actually use it?

My Controller and View are like this:

//Controller Index()
var states = GetStatesAvailable();
ViewBag.MyStates = new SelectList(states, "stateID", "Description");
return View();


//View
<script type="text/javascript">
var statesAvailable = "@ViewBag.MyStates";
//Loop through statesAvailable?
</script>

Solution

  • MVC CONTROLLER:

       //Controller Index()
        var states = GetStatesAvailable();
        var MyStates = new SelectList(states, "stateID", "Description");
        ViewBag.MyStates = JsonConvert.SerializeObject(MyStates);
        return View(); 
    

    JS:

    Just make sure that jQuery is loaded before you run that script

    <script type="text/javascript">
        var statesAvailable = @Html.Raw(ViewBag.MyStates);
        //Loop through statesAvailable
    
        $.each(statesAvailable, function (value)
        {
    
            console.log(value);
    })