0

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.

1
  • var behzad = @Html.Raw(Json.Encode(ViewBag.movies)); alert(behzad); (and not wrapped in @{ ... }) Commented Sep 5, 2016 at 13:41

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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();

1 Comment

that's work,but java script alert show me this:[{"name":"s2.picofile.com/file/7783181933/Demo_Rehlat_Imam_Khomeini.jpg "},{"name":"farsi.rouhollah.ir/image/imam.jpg "}] that is &quot.

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.