如何在jquery中读取ViewBag列表

时间:2014-08-11 17:53:00

标签: jquery asp.net-mvc viewbag

我有一个列表,我想从Controller传递给我的View并使用JQuery循环遍历列表。在我的jquery中,我可以看到ViewBag对象但是如何扩展数据以实际使用它?

我的控制器和视图是这样的:

//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>

2 个答案:

答案 0 :(得分:10)

MVC CONTROLLER:

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

<强> JS:

在运行该脚本之前,请确保已加载jQuery

<script type="text/javascript">
    var statesAvailable = @Html.Raw(ViewBag.MyStates);
    //Loop through statesAvailable

    $.each(statesAvailable, function (value)
    {

        console.log(value);
})

答案 1 :(得分:3)

试试这个;

var statesAvailable = @Html.Raw(Json.Encode(@ViewBag.MyStates));