Convert viewbag to javascript array
Asked Answered
S

1

5

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; 

} 
Superabundant answered 17/9, 2012 at 6:53 Comment(1)
Have you given ajax a try? In mvc you can use a controller action method that returns json data like: public JsonResult ActionName(){ return Json("Data", JsonRequestBehavior.AllowGet); }. You may also look at the following post: cleancode.co.nz/blog/739/ajax-aspnet-mvc-3Largescale
B
11

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>
Binnie answered 17/9, 2012 at 7:6 Comment(6)
@Pushpendra: The code you posted, should be written in <script></script> tags? If so then how could you use server variable (ViewBag) on client script. This is not efficient solution.Largescale
point one is not inside the script. It should inside the controller. and second point should be inside the script.Binnie
@Pushpendra: Javascript does not contain ArrayList type, How I will write a c sharp inside script?Superabundant
Please check it the code which i have editted. now it is tested.Binnie
@Pushpendra:it is same to my code above and, if it worked that way I will not ask my question.Superabundant
but please change the ViewBag.mytags = mp3.TagSuggestion(); to ViewBag.mytags = mp3.TagSuggestion().toList(); It is working on my system. I have checked and give you finally.Binnie

© 2022 - 2024 — McMap. All rights reserved.