Alex Rivera | Logout

Pass Array from MVC to javascript?

Asked 2010-10-03T18:15:59.957
57

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

Edit
Report

2 Answers

43

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>
answered 2010-10-04T06:34:53.220
2

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.

answered 2010-10-03T18:24:00.127

Your Answer