Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

In this controller i got all the movienames

public ActionResult MultiText()
 {
    List<string> mnames = db.AllMovienames().ToList();
    ViewBag.movies = mnames;

    return View();
}

I need to send this "ViewBag.movies" to Javascript present in view

 $(function () {

    var availableTags = ViewBag.movies;
    function split(val) {
        return val.split(/,\s*/);
    }
    function extractLast(term) {
        return split(term).pop();
    }
    $("#tags")
    // don't navigate away from the field on tab when selecting an item
  .bind("keydown", function (event) {
   if (event.keyCode === $.ui.keyCode.TAB &&
   $(this).data("ui-autocomplete").menu.active) {
    event.preventDefault();
  }
})

But i cant get values into view

share|improve this question

3 Answers 3

up vote 3 down vote accepted

You could write it out as json in your view like this:

<script type="text/javascript">
 var movies =  @Html.Raw(Json.Encode(ViewBag.movies))
</script>

If you wrap your javascript up into a function you could then pass them in i.e.

function DoThis(movies)
{
   var availableTags = movies;
    .....
}

This would allow you to call it like this:

<script type="text/javascript">
 var movies =  @Html.Raw(Json.Encode(ViewBag.movies))
 DoThis(movies);
</script>
share|improve this answer
    
I tried Json.Encode it show me an error –  user3145484 Jan 7 at 12:21
    
What is the error? –  hutchonoid Jan 7 at 12:24
    
it show compile time error.is there any assembly i need to give? –  user3145484 Jan 7 at 12:29
    
System.Web.Helpers.Json is the assembly –  hutchonoid Jan 7 at 12:36

You could put the tags into a hidden field and then retrieve them using jQuery:

View:

 @Html.Hidden("Movies", string.Join(",", ViewBag.movies))

JavaScript:

 var availableTags = $('#Movies').val().split(",");
share|improve this answer

you can use the code below:

/In Controller

/Controller/SiteConfig
public ActionResult SiteConfig()
{
     string movie = // your code
     return JavaScript("var movies ="+moive);
}
//In cshtml
@Script.Render("~/Controller/SiteConfig")

Then you can get variable movie in javascript.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.