Pass Array from MVC to javascript?

前端 未结 9 1027
难免孤独
难免孤独 2020-11-28 23:32

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

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

This work fine

相关标签:
9条回答
  • 2020-11-29 00:03

    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>
    
    0 讨论(0)
  • 2020-11-29 00:12

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

    0 讨论(0)
  • 2020-11-29 00:13

    Using Json.NET

    var yourlist = JSON.parse('@Html.Raw(JsonConvert.SerializeObject(Model.YourList))');
    
    0 讨论(0)
  • 2020-11-29 00:17

    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.

    0 讨论(0)
  • 2020-11-29 00:19

    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"}, ...];
    
    0 讨论(0)
  • 2020-11-29 00:24

    something like this:

    <script type="text/javascript">
    var myArr = [<%=string.Join(",", strArr.Select(o => "\"" + o + "\"")) %>];
    </script>
    
    0 讨论(0)
提交回复
热议问题