admin管理员组

文章数量:1134589

I can pass a variable from MVC ASP.NET by using this :

var lastCategoryId = '<%=Model.CS.LastSelectedCategory %>';

This work fine with string or integer but how do I do with an array of strings? I have tried to pass the array the same way but the variable is set to System.String[] ?

I can pass a variable from MVC ASP.NET by using this :

var lastCategoryId = '<%=Model.CS.LastSelectedCategory %>';

This work fine with string or integer but how do I do with an array of strings? I have tried to pass the array the same way but the variable is set to System.String[] ?

Share Improve this question edited Mar 2, 2012 at 11:49 dif 2,4936 gold badges38 silver badges51 bronze badges asked Oct 3, 2010 at 18:15 BansheeBanshee 15.8k41 gold badges138 silver badges231 bronze badges
Add a comment  | 

9 Answers 9

Reset to default 171 +50

You could let .NET handle all the heavy lifting for you with this simple line of code.

This assumes you're using MVC Razor syntax.

var yourJavaScriptArray = @Html.Raw(Json.Encode(Model.YourDotNetArray));

For newer versions of MVC, use:

var yourJavaScriptArray = @Html.Raw(Json.Serialize(Model.YourDotNetArray));

You could JSON serialize it. This way could could pass even more complex values and not worry about escaping simple quotes, double quotes, etc :

var categoriesList = <%= new JavaScriptSerializer().Serialize(new[] { "value1", "value2" }) %>;

Writing an HTML helper to do this would be even better:

public static class HtmlExtensions
{
    public static string JsonSerialize(this HtmlHelper htmlHelper, object value)
    {
        return new JavaScriptSerializer().Serialize(value);
    }
}

and then in your view:

<script type="text/javascript">
    var categoriesList = <%= Html.JsonSerialize(new[] { "value1", "value2" }) %>;
</script>

This should do

var someArray=[<%foreach (var s in myStringArray){%>'<%=s%>',<%}%>];

something like this:

<script type="text/javascript">
var myArr = [<%=string.Join(",", strArr.Select(o => "\"" + o + "\"")) %>];
</script>

One liner:

var data = [@Html.Raw(String.Join(",", Model.MyArray.Select(i => "'" + i + "'")))];

So easy, so simple

<script type="text/javascript">
    var array = @Html.Raw(
        Json.Encode(
            (Model).Select(m=> new 
            { 
                id= m.ID, 
                name=m.Name
            })
        )
    );
</script>

Output is:

[{"id":1,"name":"Name of 1"}, {"id":2,"name":"Name of 2"}, ...];

Using Json.NET

var yourlist = JSON.parse('@Html.Raw(JsonConvert.SerializeObject(Model.YourList))');

You need to format the array into a JavaScript array syntax.

var someArray = [<%= Model.SomeArray.Select(x => "'" + x +"'")
                           .Aggregate((x,y) => x + ", " + y);  %>];

This will surround each entry by single quotes and then join them together with commas between square brackets.

Updated: removed extra parenthesis.

Just wanted to provide an answer using Razor syntax:

We have a Dictionary<int, int> that we are rendering for a jQuery Sparkline, in the form of "an array of arrays".

var usageData = [ @string.Join(",", Model.UsageData.Select(d => string.Format("[{0},{1}]", d.Key, d.Value)).ToArray()) ];

Which is used like so:

$('#sparkline').UsageSparkline(usageData, { tooltipFormatter: cachedTooltips });

This is what we get when viewing the source:

var usageData = [ [-13,0],[-12,1],[-11,0],[-10,0],[-9,1],[-8,1],[-7,0],[-6,2],[-5,2],[-4,0],[-3,0],[-2,9],[-1,3],[0,4] ];
$('#sparkline').UsageSparkline(usageData, { tooltipFormatter: cachedTooltips });

本文标签: aspnet mvcPass Array from MVC to javascriptStack Overflow