Generate a raw json array in a view in ASP.NET MVC

I am using ASP.NET MVC and I am trying to create a javascript part as part of a view rendering. I have a model that exposes an array of simple types, and I would like to create an equivalent javascript / json array in the view so that I can work on it using jQuery. So, given the following model:

public class Info {
   public string Name {get;set;}
   public int ID {get; set;}
}

public class InfoModel{
   public Info[] InfoList {get;set;}
}

... I would like to create a javascript array that looks like this:

var infoList = [
      {
         Name = "...",
         ID = 1
      } ,
      {
         Name = "...",
         ID = 2
      },
      ....
      {
         Name = "...",
         ID = N
      }];

Is there a good and concise way to do this in the view, I seem to be having problems with quoting quotes if I try to create a model to generate the json representation, so for now I can only create it using some spaghetti / classic asp- code that I would rather replace with a good one-liner.

EDIT: : , JsonResult, , javascript, ( )

EDIT: , , , . :

<script>
var list = <%: HtmlExtension.ToJson(Model.InfoList) %>;
</script>

( ToJson JavaScriptSerializer) :

var info = [{&quot;Name&quot;:&quot;Low End&quot;,&quot;ID&quot;:1}];

.. , . :

var info = <% Response.Write(HtmlExtension.ToJson(Model.InfoList)); %>;

, . , ( , , ), - , asp?

+5
2

, . , :

  • , , MvcHtmlString string ...
  • , <%: ... %> , <%= ... %>, .
+5

, :

InfoModel viewModel; // get this from wherever
return Json(viewModel);

MVC JSON.

JsonResult (.. raw JSON).

, ?

- :

<script type="text/javascript>
   var json = <%: Model.JsonStuff %>
   // more js
</script>

.

, ViewModel.

, .

JavaScriptSerializer js = new JavaScriptSerializer();
var listOfInfos; // this will be a collection (e.g List) of Infos.
var viewModel = new InfoModel
                {
                   InfoList = js.Serialize(listOfInfos);
                };
return View(viewModel);

listOfInfo IEnumerable, JSON.

, , .

+1

All Articles