Note that there are some explanatory texts on larger screens.

plurals
  1. POGenerate raw json array into view in ASP.NET MVC
    text
    copied!<p>I'm using ASP.NET MVC and I'm trying to generate a piece of javascript as part of the view rendering. I have a model that expose an array of simple types and I would like to generate a javascript/json equivalent array into the view so that I can act on it using jQuery. So given the following model:</p> <pre><code>public class Info { public string Name {get;set;} public int ID {get; set;} } public class InfoModel{ public Info[] InfoList {get;set;} } </code></pre> <p>...I would like to generate a javascript array looking like this:</p> <pre><code>var infoList = [ { Name = "...", ID = 1 } , { Name = "...", ID = 2 }, .... { Name = "...", ID = N }]; </code></pre> <p>Is there a nice and concise way to do this in the view, I seem to have trouble with encoding of quotes if I try to have the model generate a json representation, so currently I can only have it generated using some spaghetti/classic asp code that I would rather have replaced by a nice one-liner.</p> <p>EDIT: Note that I'm not looking for away to have a controller return a JsonResult, I want a way for my view to contain a javascript array that is generated from my model in a single line of code (if possible)</p> <p>EDIT: I got part of the way, but seems to be struggling with encoding. This code in the view:</p> <pre><code>&lt;script&gt; var list = &lt;%: HtmlExtension.ToJson(Model.InfoList) %&gt;; &lt;/script&gt; </code></pre> <p>(where ToJson encapsulates conversion to string using JavaScriptSerializer) outputs some encoding faults:</p> <pre><code>var info = [{&amp;quot;Name&amp;quot;:&amp;quot;Low End&amp;quot;,&amp;quot;ID&amp;quot;:1}]; </code></pre> <p>..which is not what I was looking for. I could do this:</p> <pre><code>var info = &lt;% Response.Write(HtmlExtension.ToJson(Model.InfoList)); %&gt;; </code></pre> <p>which works, but doesn't look as shiny. Should I explicitly ignore encoding as shown (The output is sane, not user generated, so it may not be a problem) or am I missing something else that makes it less classic asp?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload