jQuery 如何在jquery中读取ViewBag列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25249443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:04:18  来源:igfitidea点击:

How to read ViewBag list in jquery

jqueryasp.net-mvcviewbag

提问by Jerry

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?

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

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>

回答by sylwester

MVC CONTROLLER:

MVC控制器:

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

JS:

JS:

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

只需确保在运行该脚本之前加载了 jQuery

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

    $.each(statesAvailable, function (value)
    {

        console.log(value);
})

回答by Kinjal Gohil

try this;

尝试这个;

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