Pass Array from MVC to javascript?

前端 未结 9 1028
难免孤独
难免孤独 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:27

    One liner:

    var data = [@Html.Raw(String.Join(",", Model.MyArray.Select(i => "'" + i + "'")))];
    
    0 讨论(0)
  • 2020-11-29 00:30

    This should do

    var someArray=[<%foreach (var s in myStringArray){%>'<%=s%>',<%}%>];
    
    0 讨论(0)
  • 2020-11-29 00:30

    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 });
    
    0 讨论(0)
提交回复
热议问题