将 viewbag 转换为 javascript 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12454371/
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-10-26 16:14:26 来源:igfitidea点击:
Convert viewbag to javascript array
提问by dr ammar
I want to get the data from the ViewBag.mytags to a Javascript array, but I was not able to avhice this
我想从 ViewBag.mytags 获取数据到一个 Javascript 数组,但我无法做到这一点
$(function () {
var sampleTags = new Array();
var array = @Html.Raw(Json.Encode(@ViewBag.mytags));
for(var i =0; i<array.length;i++){
sampleTags[i] = array[i];
}
$('#singleFieldTags').tagit({
availableTags: sampleTags,
singleField: true,
singleFieldNode: $('#mySingleField')
});
}
This is my controller
这是我的控制器
ViewBag.mytags = mp3.TagSuggestion();
This is my Models
这是我的模特
public IQueryable<string> TagSuggestion()
{
IQueryable<string> tabs = from s in db.tblTags select s.Title;
return tabs;
}
回答by Pushpendra
Please follow these step
请按照以下步骤操作
public IList<string> TagSuggestion()
{
IQueryable<string> tabs = from s in db.tblTags select s.Title;
return tabs.toList();
}
Inside MVC Contoller :
MVC 控制器内部:
ViewBag.mytags = mp3.TagSuggestion().toList();
In view:
鉴于:
<script>
$(function () {
var sampleTags = new Array();
var array = @Html.Raw(Json.Encode(@ViewBag.mytags));
for(var i =0; i<array.length;i++){
sampleTags[i] = array[i];
}
$('#singleFieldTags').tagit({
availableTags: sampleTags,
singleField: true,
singleFieldNode: $('#mySingleField')
});
});
</script>