Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Array from MVC to javascript?

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[] ?

like image 919
Banshee Avatar asked Oct 03 '10 18:10

Banshee


4 Answers

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

like image 72
James Mikesell Avatar answered Oct 21 '22 22:10

James Mikesell


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>
like image 35
Darin Dimitrov Avatar answered Oct 21 '22 22:10

Darin Dimitrov


This should do

var someArray=[<%foreach (var s in myStringArray){%>'<%=s%>',<%}%>];
like image 16
Adrian Grigore Avatar answered Oct 21 '22 21:10

Adrian Grigore


something like this:

<script type="text/javascript">
var myArr = [<%=string.Join(",", strArr.Select(o => "\"" + o + "\"")) %>];
</script>
like image 3
Omu Avatar answered Oct 21 '22 21:10

Omu