下拉列表未返回正确的值

本文关键字:返回 下拉列表 | 更新日期: 2023-09-27 18:20:37

我正在尝试检索以前数据绑定的DropDownList上的值,如下所示:

<asp:DropDownList ID="DropDownListReception" runat="server" CssClass="span3 drop-down-reception"
            OnPreRender="DropDownListReception_PreRender" OnSelectedIndexChanged="DropDownListReception_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
    {
        var receptions = BLLFactory.ReceptionBLL.GetListAll();
        DropDownListReception.DataSource = receptions;
        DropDownListReception.DataBind();
    }

在DropDown预渲染上,我正在像这样个性化这个DropDown:

protected void DropDownListReception_PreRender(object sender, EventArgs e)
    {
        if (DropDownListReception.DataSource != null)
        {
            DropDownListReception.Items.Clear();
            DropDownListReception.Items.Add(new ListItem("-- Select --", "NA"));
            foreach (Reception item in (DropDownListReception.DataSource as IEnumerable))
            {
                DropDownListReception.Items.Add(new ListItem(item.Name + " " + item.Number, item.Id.ToString()));
            }
        }
    }

这运行得很好,我的DropDown加载正常,我的问题是当我试图在SelectedIndexChanged事件中检索SelectedValue时,它不会以字符串的形式返回值,而是以类型的形式返回,我正在做的是:

protected void DropDownListReception_SelectedIndexChanged(object sender, EventArgs e)
    {
        //CurrentReception is a string i want to save in ViewState
        //I also tried (sender as DropDownList).SelectedValue
        //Tried DropDownListReception.SelectedValue
        CurrentReception = DropDownListReception.SelectedItem.Value;
    }

但是这个"DropDownListReception.SelectedItem.Value"将始终返回"Reception",这是项目的类型,而不是在PreRender事件中指定为项目值的id i。如果我这样做,也会发生这种情况:"DropDownListReception.SelectedItem.Text",这也会返回"Reception"。如何返回分配给DropDown项目的字符串Value?

下拉列表未返回正确的值

var CurrentReception = DropDownListReception.SelectedItem as Reception;
string val = CurrentReception.PropertyYouNeed;

DropDownListReception.SelectedItem.Text和DropDownList Reception.SectiedItem.Value将返回所选内容的值,这是将ListItem添加到列表时使用的ListItem中的第二个术语。换句话说,问题出在项目上。Id.ToString()。它返回对象的类型,而不是Id。我不确定您的item对象实际上由什么组成,所以我不确定你实际需要什么,但你确定它不仅仅是item吗。Id?ToString()通常是对象if项的字符串表示形式。Id是一个int,那么ToString应该为您提供与该int等价的字符串……但它不起作用的事实表明是项。Id实际上不是int。

我认为你需要将列表项强制转换为你存储在其中的类型(Reception),然后从你想要的Reception对象访问属性(从你的描述中,听起来你想要id)。像这样:

protected void DropDownListReception_SelectedIndexChanged(object sender, EventArgs e)
{
    //CurrentReception is a string i want to save in ViewState
    CurentReception = ((Reception)DropDownListReception.SelectedItem).Id.ToString();
}

我发现了,我在PageLoad上DataBinding DropDownList,它在SelectedIndexChanged事件之前触发。由于DropDown在其值更改时执行PostBack,因此PageLoad正在"重新创建"DropDown,而我在获取SelectedIndexChanged代码之前丢失了更改。

谢谢大家的回答。:)