behzad razzaqi behzad razzaqi - 1 year ago 159
Javascript Question

How to pass list from controller to javascript function in mvc?

I have this query in the controller:

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

return View();

and write this java script code in view page:

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



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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download