转换viewbag的JavaScript阵列(Convert viewbag to javascri

2019-09-22 12:09发布

我想从ViewBag.mytags到Javascript数组中的数据,但我没能avhice这

$(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')
    });
}

这是我的控制器

ViewBag.mytags = mp3.TagSuggestion();

这是我的模型

public IQueryable<string> TagSuggestion() 
{ 

    IQueryable<string> tabs = from s in db.tblTags select s.Title; 

    return tabs; 

} 

Answer 1:

请按照以下步骤

public IList<string> TagSuggestion() 
{ 
    IQueryable<string> tabs = from s in db.tblTags select s.Title; 
    return tabs.toList(); 
}

里面MVC位指示:

ViewBag.mytags = mp3.TagSuggestion().toList();

鉴于:

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


文章来源: Convert viewbag to javascript array