behzad razzaqi behzad razzaqi - 3 months ago 11
Javascript Question

How to pass list from controller to javascript function in asp.net mvc?

I have this query in the controller:


DataClasses1DataContext behzad = new DataClasses1DataContext();
var query = (from p in behzad.ImagePaths
select new
{
p.name
}).ToList();
ViewBag.movies = query;


return View();




and write this java script code in view page:


function behi() {
@{
var behzad = ViewBag.movies;
}

alert('@(behzad)');


}




that java script code show me this:

enter image description here


how can i write java script code for show controller query result?thanks all.

Answer

Serialize it. The below code use Newtonsoft's Json serializer to do so.

var movies = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.movies));

Now the movies variable will be an array of items, each with a name property.

Comments