Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert viewbag to javascript array

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; 

} 
like image 831
dr ammar Avatar asked Sep 17 '12 06:09

dr ammar


1 Answers

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>
like image 183
Pushpendra Avatar answered Oct 15 '22 06:10

Pushpendra