Convert viewbag to javascript array

血红的双手。 提交于 2019-12-14 01:23:22

问题


I want to get the data from the ViewBag.mytags to a Javascript array, but I was not able to avhice this

$(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; 

} 

回答1:


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 :

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>


来源:https://stackoverflow.com/questions/12454371/convert-viewbag-to-javascript-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!