如何在javascript ASP.NET中从会话中获取对象列表

本文关键字:会话 取对象 列表 获取 NET javascript ASP | 更新日期: 2023-09-27 18:07:57

我已经从复选框列表中动态创建了复选框,并将此列表保存到会话中,并希望在复选框的onChange事件中从会话中获取此复选框列表。这是代码。

    public static List <CheckBox> chklist = new List <CheckBox> ();
    void arrinit() {
        for (int i = 0; i < 31; i++) {
            //initializing list of checkboxes
            chklist.Add(new CheckBox());
        }
    }
    void show() {
        for (int i = 0; i < 30; i++) {
            TableCell cell4 = new TableCell();
            tRow.Cells.Add(cell4);
            ((IParserAccessor) cell4).AddParsedSubObject(chklist[i]);
            chklist[i].ID = "cbx_" + i.ToString();
            string a = "processChechBox('" + "ctl00_ContentPlaceHolder1_" + chklist[i].ID + "'); return false;";
            chklist[i].Attributes.Add("onChange", a);
            chklist[i].Attributes.Add("runat", "server");
        }
        Session["chk"] = chklist;
    }
    function processChechBox(id) {
        //here is the javascript function for checkbox onChange event
        debugger;
        var containerRef = document.getElementById(id);
        var data = document.getElementById(id);
        data.value = '1';
        data.checked = true;
        var a = '<%= Session["chk"]%>';
    }

var a = '<%= Session["chk"]%>';此行返回的是System.Collections.Generic.List1[System.CheckBox]而不是列表processChechBox(id)在选中的每个复选框上调用此函数。

如何在javascript ASP.NET中从会话中获取对象列表

此行

<%= Session["chk"]%>

将写出相当于的内容

Session["chk"].ToString()

这显然不是你想要的。使用这里使用的"var a"可以完成什么?

我猜你真的想要这样的

<% var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); %>
var jsVariable = <%= serializer.Serialize(((List<CheckBox>)Session["chk"]).ToArray()) %>;

来源:将C#ASP.NET数组传递给Javascript数组

尝试以下方法并检查控制台日志中的内容。

function processChechBox(id) {
//here is the javascript function for checkbox onChange event
debugger;
var containerRef = document.getElementById(id);
var data = document.getElementById(id);
data.value = '1';
data.checked = true;
var list = <%= new JavaScriptSerializer().Serialize(Session["chk"]) %>;
console.log(list);

}