在 foreach 循环中的 javascript 代码中调用 ASPX 代码后面的列表?

Call a list in code behind of ASPX , in javascript code in foreach loop?

我有以下 aspx.cs :

public partial class BarChart 
{
    public class LabelsDetail
    {
        public string LabelId { get;set; }
        public string LabelDesc { get; set; }
    }
    public List<LabelsDetail> LabelsDetails { get; set; }

    public void InsertDataToLabelsDetails()
    {
        // Data comes from somewhere into "LabelsDetails"

    }

}

以及 ASPX 页面中的以下 JS 代码:

        function setupBarChart(JQObjectContainer, JsonData) {
            var hashTableSize = <%=this.LabelsDetails.Count%>;
            var hashtable = {};

            if (hashTableSize != 'undefined' && hashTableSize > 0)
            {
                for (var item in <%=this.LabelsDetails%>)
                { 
                    hashtable[item.LabelId] = item.LabelDesc;
                }
            }

}

如何在客户端的服务器端列表上执行 foreach?

此刻我得到Uncaught SyntaxError: Unterminated template literal 当我尝试在服务器端列表 (this.LabelsDetails) 上循环时。

谢谢

您必须将您的集合转换为 JavaScript 可以理解的符号,为此您可以使用 JavaScriptSerializer 或任何其他 JSON 转换器:

var collection = new[]{
    new { Name = "a" },
    new { Name = "b" },
    new { Name = "c" },
    new { Name = "d" }
};

System.Web.Script.Serialization.JavaScriptSerializer s = new System.Web.Script.Serialization.JavaScriptSerializer();

Console.WriteLine(s.Serialize(collection));

这将输出 [{"Name":"a"},{"Name":"b"},{"Name":"c"},{"Name":"d"}],这是 JavaScript 的有效数组表示法。您还可以改进在 JS 中迭代的方式:

var array = <%=new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(this.LabelsDetails)%>;
for(var x=0;x<array.length;x++)
{ 
    hashtable[array[x].LabelId] = array[x].LabelDesc;
}

For...In在JS中不好遍历数组,和C#中的foreach不一样

来自MDN

Array iteration and for...in

Note: for..in should not be used to iterate over an Array where the index order is important. Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.

但是,可能值得回顾一下您的方法并使用其他技术在客户端和服务器端之间建立连接。

试试这个

function setupBarChart(JQObjectContainer, JsonData) {
            var hashTableSize = <%=this.LabelsDetails.Count%>;
            var hashtable = {};
            var json = <%=new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(this.LabelsDetails)%>;
            if (hashTableSize != 'undefined' && hashTableSize > 0)
            {
                for (var key in json)
                { 
                    hashtable[json[key].LabelId] = json[key].LabelDesc;
                }

            }
}