【问题标题】:Keeping the selected values in programmatically created DropDownList after button click ASP.NET在按钮单击 ASP.NET 后将所选值保留在以编程方式创建的 DropDownList 中
【发布时间】:2018-05-21 23:58:01
【问题描述】:

我创建了一个表单,在其中添加基于 PDF 表单字段的下拉列表。

namesMapping 变量是一个 Dictionary,其中包含旧值作为键和新值作为值。要保存值,我想将当前选择添加到Dictionary。 但事件监听器没有触发。

我在这里读过很多帖子说使用IsPostBack 变量来不更新页面重新加载时的下拉菜单。但在这种情况下它似乎不起作用。

感觉从下拉列表中获取所选值应该更容易。但无论如何,如何保存下拉列表中的选定值,以便在单击按钮后获取它们?

代码如下:

    protected void Page_Load(object sender, EventArgs e)
    {
        ListItem[] listItems = new ListItem[4];
        listItems[0] = new ListItem("First Name", "first-name");
        listItems[1] = new ListItem("Last Name", "last-name");
        listItems[2] = new ListItem("Email", "email");
        listItems[3] = new ListItem("Company", "company");

        int counter = 0;
        foreach (PdfField field in fields)
        {
            if (field.GetType() == typeof(PdfTextField))
            {
                TableRow tr = new TableRow();
                TableCell name = new TableCell
                {
                    Text = field.Name
                };
                tr.Cells.Add(name);
                TableCell options = new TableCell();

                DropDownList dropdown = new DropDownList();
                dropdown.ID = field.Name;
                for (int i = 0; i < listItems.Length; i++)
                {
                    dropdown.Items.Add(listItems[i]);
                }
                dropdown.SelectedIndexChanged += Dropdown_SelectedIndexChanged;

                options.Controls.Add(dropdown);
                tr.Cells.Add(options);
                Table1.Rows.Add(tr);

                //If page loads for the first time, set the mapping to the default selected values
                if (!IsPostBack)
                {
                    namesMapping.Add(field.Name, dropdown.SelectedValue);
                }
            }
        }

    private void Dropdown_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList dropDown = (DropDownList) sender;
        namesMapping[dropDown.ID] = dropDown.SelectedValue;
    }

感谢您的回答。

编辑

我将创建下拉菜单的代码移到if(!IsPostBack) 内,因此在重新加载页面时不会重新创建它们。我将所有下拉列表保存在 Dictionary 中,但当在下拉列表中选择另一个值时,它们仍将第一个值显示为已选择。

代码如下:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            doc = new PdfDocument(pdfFileName);

            namesMapping = new Dictionary<string, string>();
            ddlMappings = new Dictionary<string, DropDownList>();

            //Get all fields
            fields = doc.Fields;

            //Create the dropdown lists
            dropdownLists = new List<DropDownList>();

            ListItem[] listItems = new ListItem[4];
            listItems[0] = new ListItem("First Name", "first-name");
            listItems[1] = new ListItem("Last Name", "last-name");
            listItems[2] = new ListItem("Email", "email");
            listItems[3] = new ListItem("Company", "company");

            int counter = 0;
            foreach (PdfField field in fields)
            {
                //Only display the text fields
                if (field.GetType() == typeof(PdfTextField))
                {
                    TableRow tr = new TableRow();
                    //Add the field name
                    TableCell name = new TableCell
                    {
                        Text = field.Name
                    };
                    tr.Cells.Add(name);
                    //Add the options to select from
                    TableCell options = new TableCell();

                    DropDownList dropdown = new DropDownList();
                    dropdown.ID = field.Name;

                    //Populate the dropdown
                    for (int i = 0; i < listItems.Length; i++)
                    {
                        dropdown.Items.Add(listItems[i]);
                    }

                    dropdown.AutoPostBack = true;
                    dropdown.SelectedIndexChanged += Dropdown_SelectedIndexChanged;

                    options.Controls.Add(dropdown);
                    tr.Cells.Add(options);
                    //Add row to table
                    Table1.Rows.Add(tr);

                    //If page loads for the first time, set the mapping to the default selected values
                    namesMapping.Add(field.Name, dropdown.SelectedValue);
                    ddlMappings.Add(field.Name, dropdown);
                }
            }

        }
        else
        {
            foreach (PdfField field in fields)
            {
                //Only display the text fields
                if (field.GetType() == typeof(PdfTextField))
                {
                    TableRow tr = new TableRow();
                    //Add the field name
                    TableCell name = new TableCell
                    {
                        Text = field.Name
                    };
                    tr.Cells.Add(name);
                    //Add the options to select from
                    TableCell options = new TableCell();

                    DropDownList dropdown = ddlMappings[field.Name];
                    dropdown.SelectedIndexChanged += Dropdown_SelectedIndexChanged;

                    options.Controls.Add(dropdown);
                    tr.Cells.Add(options);
                    //Add row to table
                    Table1.Rows.Add(tr);

                }
            }

        }

        if (!IsPostBack)
        {
            foreach(var ddl in ddlMappings)
            {
                ddl.Value.SelectedValue = namesMapping[ddl.Key];
            }
        }
    }


    private void Dropdown_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList dropDown = (DropDownList) sender;
        namesMapping[dropDown.ID] = dropDown.SelectedValue;
    }

【问题讨论】:

  • 您是否遇到任何错误或 SelectedIndexChanged 事件根本没有触发??
  • 刚刚发现除非我添加AutoPostBack = true,否则它不会触发,除非我添加AutoPostBack = true,但它会在页面重新加载后触发并且我丢失了选定的值。
  • 您是否尝试过将所有代码放入 if(!Page.IsPostBack) 中???您正在失去您的价值,因为每次更改选择时您的下拉列表都会绑定。尝试将所有代码放入 if 块中并查看。
  • 如果我这样做,表格是空的并且没有下拉菜单。
  • 管理一个 Dictionary&lt;string, DropDownList&gt;,它将 DropDownList ID 映射到对象本身,并与 namesMapping 一起填充。然后在Page_Load 的末尾添加一个循环,该循环遍历字典中的所有对象,并根据namesMapping 字典中的正确条目设置它们的 SelectedValue 属性。这将允许您在页面重新加载之间保留列表选择的最新状态。

标签: c# asp.net webforms


【解决方案1】:

如果您在 Page_Load 中进行数据绑定,那么您也在重置 SelectedItem。

您应该将存在于Page_Load 中的绑定代码添加到if(!IsPostBack) 块内。

if(!Page.IsPostBack)
{

    // Your binding code here ...

}

这是您进行绑定的代码示例...

 <form id="form1" runat="server">
<div>
    <asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
</div>
</form>
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack) {
            Bind();
        }


    }


protected void Bind() {
        DataTable dt = new DataTable();
        DataColumn dc = new DataColumn("Name", typeof(string));
        DataColumn dc2 = new DataColumn("Path", typeof(string));


        dt.Columns.Add(dc);
        dt.Columns.Add(dc2);

        DataRow dr = dt.NewRow();
        dr["Name"] = "1";
        dr["Path"] = Server.MapPath("ProDinner1.pdf");

        DataRow dr2 = dt.NewRow();
        dr2["Name"] = "2";
        dr2["Path"] = Server.MapPath("ProDinner2.pdf");

        dt.Rows.Add(dr);
        dt.Rows.Add(dr2);

        DropDownList1.DataSource = dt;
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "Path";
        DropDownList1.DataBind();
    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string path = DropDownList1.SelectedValue.ToString();
        Session["path"] = path;
        Response.Write("<script language=javascript>window.open('show.aspx')</script>");



    }

【讨论】:

  • 我试过了,但还是不行。下拉菜单保持相同的值。
【解决方案2】:

看了这篇文章,我找到了解决问题的办法:

Maintain The State Of Dynamic Added User Control On Each PostBack

我使用ViewState 保存下拉列表的 ID,以便能够在回发时重新创建它们。代码如下:

public Dictionary<Guid, string> DropdownLists
{
    get { return ViewState["MyDropdowns"] != null
            ? (Dictionary<Guid, string>)ViewState["MyDropdowns"] : new Dictionary<Guid, string>(); }
    set { ViewState["MyDropdowns"] = value; }
}

public Dictionary<Guid, string> DropdownNames
{
    get { return ViewState["DropdownNames"] != null
    ? (Dictionary<Guid, string>)ViewState["DropdownNames"] : new Dictionary<Guid, string>(); }
    set { ViewState["DropdownNames"] = value; }
}

首先我添加了这两个类变量,它们将它们的值保存在ViewState 中。然后,当页面第一次加载时,方法CreateForm() 被调用,该方法根据 PDF 文件中的字段创建所有下拉列表。当页面在回发时加载时,下拉菜单是根据存储在ViewState 中的值创建的。代码如下:

protected void Page_Load()
{

    //Load the file
    doc = new PdfDocument(pdfFileName);

    //Get all fields
    fields = doc.Fields;

    if (!IsPostBack)
    {
        CreateForm();
    }
    else
    {
        RecreateForm();
    }
}

private void CreateForm()
{

    Dictionary<Guid, string> tempList = new Dictionary<Guid, string>();
    Dictionary<Guid, string> tempNames = new Dictionary<Guid, string>();

    foreach (PdfField field in fields)
    {
        //Only display the text fields
        if (field.GetType() == typeof(PdfTextField))
        {
            TableRow tr = new TableRow();
            TableCell name = new TableCell
            {
                Text = field.Name
            };
            tr.Cells.Add(name);
            TableCell options = new TableCell();

            DropdownList dropdown = (DropdownList)LoadControl("~/DropdownList.ascx");

            Guid nextKey = Guid.NewGuid();
            tempList[nextKey] = "dropdown" + nextKey.ToString().Replace('-', '_');
            dropdown.ID = tempList[nextKey];

            tempNames[nextKey] = field.Name;

            options.Controls.Add(dropdown);
            tr.Cells.Add(options);

            Table1.Rows.Add(tr);
        }
    }
    DropdownLists = tempList;
    DropdownNames = tempNames;
}

private void RecreateForm()
{
    foreach (var item in DropdownLists)
    {
        TableRow tr = new TableRow();
        TableCell name = new TableCell
        {
            Text = DropdownNames[item.Key]
        };
        tr.Cells.Add(name);
        TableCell options = new TableCell();

        DropdownList dropdown = (DropdownList)LoadControl("~/DropdownList.ascx");

        dropdown.ID = DropdownLists[item.Key];

        options.Controls.Add(dropdown);
        tr.Cells.Add(options);

        Table1.Rows.Add(tr);
    }
}

我希望这可以帮助任何人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-09
    • 2011-06-12
    • 2013-10-09
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    • 2014-11-23
    相关资源
    最近更新 更多