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.

share|improve this question
    
var behzad = @Html.Raw(Json.Encode(ViewBag.movies)); alert(behzad); (and not wrapped in @{ ... }) – Stephen Muecke 21 hours ago
up vote 1 down vote accepted

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.

share|improve this answer

Serialize return object to json like below, and use it in the javascript. JavaScriptSerializer class is in System.Web.Script.Serialization package. Hope this helps.

DataClasses1DataContext behzad = new DataClasses1DataContext();
            var query = (from p in behzad.ImagePaths
                         select new
                         {
                             p.name
                         }).ToList();
            ViewBag.movies = new JavaScriptSerializer().Serialize(query);
            return View();
share|improve this answer
    
that's work,but java script alert show me this:[{"name":"s2.picofile.com/file/778318193‌​3/Demo_Rehlat_Imam_K‌​homeini.jpg "},{"name":"farsi.rouhollah.ir/image/ima‌​m.jpg "}] that is &quot. – behzad razzaqi 21 hours ago

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.