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; 

} 
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-3 Commented Sep 17, 2012 at 8:20

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

6 Comments

@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.
point one is not inside the script. It should inside the controller. and second point should be inside the script.
@Pushpendra: Javascript does not contain ArrayList type, How I will write a c sharp inside script?
Please check it the code which i have editted. now it is tested.
@Pushpendra:it is same to my code above and, if it worked that way I will not ask my question.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.