简体   繁体   English

ASP.NET / C#:DropDownList在服务器控件中没有触发的SelectedIndexChanged

[英]ASP.NET / C#: DropDownList SelectedIndexChanged in server control not firing

I'm creating a server control that basically binds two dropdown lists, one for country and one for state, and updates the state dropdown on the country's selectedindexchanged event. 我正在创建一个服务器控件,基本上绑定两个下拉列表,一个用于国家,一个用于州,并更新国家/地区的selectedindexchanged事件的状态下拉列表。 However, it's not posting back. 但是,它没有回发。 Any ideas why? 有什么想法吗? Bonus points for wrapping them in an UpdatePanel (having rendering issues; maybe because I don't have a Page to reference?) 将它们包装在UpdatePanel中的加分点(有渲染问题;也许是因为我没有要引用的页面?)

Here's what I have (with some extra data access stuff stripped out): 这就是我所拥有的(一些额外的数据访问内容被剥离):

public class StateProv : WebControl
{
    public string SelectedCountry;
    public string SelectedState;

    private DropDownList ddlCountries = new DropDownList();
    private DropDownList ddlStates = new DropDownList();

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        IList<Country> countries = GetCountryList();
        IList<State> states = new List<State>();

        if (SelectedCountry != null && SelectedCountry != "")
        {
            states = GetStateList(GetCountryByShortName(SelectedCountry).CountryShortName);
        }
        else
        {
            states.Add(new State { CountryId = 0, Id = 0, StateLabelName = "No states available", StateLongName = "No states available", StateShortName = "" });
        }

        ddlCountries.DataSource = countries;
        ddlCountries.DataTextField = "CountryLongName";
        ddlCountries.DataValueField = "CountryShortName";
        ddlCountries.SelectedIndexChanged += new EventHandler(ddlCountry_SelectedIndexChanged);
        ddlCountries.AutoPostBack = true;

        ddlStates.DataSource = states;
        ddlStates.DataTextField = "StateLongName";
        ddlStates.DataTextField = "StateShortName";

        ddlCountries.DataBind();
        ddlStates.DataBind();

        if (!string.IsNullOrEmpty(SelectedCountry))
        {
            ddlCountries.SelectedValue = SelectedCountry;

            if (!string.IsNullOrEmpty(SelectedState))
            {
                ddlStates.SelectedValue = SelectedState;
            }
        }            
    }


    protected override void RenderContents(HtmlTextWriter output)
    {
        ddlCountries.RenderControl(output);
        ddlStates.RenderControl(output);
    }

    private IList<Country> GetCountryList()
    {
        //return stuff
    }

    private IList<State> GetStateList(Country country)
    {
        //return stuff
    }

    private IList<State> GetStateList(string countryAbbrev)
    {
        Country country = GetCountryByShortName(countryAbbrev);
        return GetStateList(country);
    }

    private Country GetCountryByShortName(string countryAbbrev)
    {
        IList<Country> list = dataAccess.RetrieveQuery<Country>();
        //return stuff
    }

    private IList<State> GetAllStates()
    {
        //return stuff
    }

    protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
    {
        IList<State> states = GetStateList(GetCountryList()[((DropDownList)sender).SelectedIndex]);
        ddlStates.DataSource = states;
        ddlStates.DataBind();
    }
}

Edit: Viewstate is on the page, and other controls on the page perform postbacks correctly, just not this. 编辑: Viewstate在页面上,页面上的其他控件正确执行回发,而不是这个。

Is Viewstate turned on? Viewstate是否已开启?

Edit: Perhaps you should reconsider overriding the rendering function 编辑:也许您应该重新考虑覆盖渲染功能

  protected override void RenderContents(HtmlTextWriter output)
    {
        ddlCountries.RenderControl(output);
        ddlStates.RenderControl(output);
    }

and instead add the dropdownlists to the control and render the control using the default RenderContents. 而是将下拉列表添加到控件并使用默认的RenderContents呈现控件。

Edit: See the answer from Dennis which I alluded to in my previous comment: 编辑:请参阅丹尼斯的答案,我在之前的评论中提到过:

Controls.Add ( ddlCountries );
Controls.Add ( ddlStates );

I can't see that you're adding these controls to the control hierarchy. 我无法看到您将这些控件添加到控件层次结构中。 Try: 尝试:

Controls.Add ( ddlCountries );
Controls.Add ( ddlStates );

Events won't be invoked unless the control is part of the control hierarchy. 除非控件是控件层次结构的一部分,否则不会调用事件。

You need to set AutoPostBack to true for the Country DropDownList . 您需要为Country DropDownListAutoPostBack设置为true。

protected override void OnLoad(EventArgs e)
{
    // base stuff

    ddlCountries.AutoPostBack = true;

    // other stuff
}

Edit 编辑

I missed that you had done this. 我错过了你做过这件事。 In that case you need to check that ViewState is enabled. 在这种情况下,您需要检查ViewState是否已启用。

I had the same problem but got round it by setting AutoPostBack to true and in an update panel set the trigger to the dropdownlist control id and event name to SelectedIndexChanged eg 我有同样的问题,但通过将AutoPostBack设置为true来绕过它,并在更新面板中将触发器设置为dropdownlist控件ID和事件名称为SelectedIndexChanged,例如

    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always" enableViewState="true">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="ddl1" EventName="SelectedIndexChanged" />
        </Triggers>
        <ContentTemplate>
            <asp:DropDownList ID="ddl1" runat="server" ClientIDMode="Static" OnSelectedIndexChanged="ddl1_SelectedIndexChanged" AutoPostBack="true" ViewStateMode="Enabled">
                <asp:ListItem Text="--Please select a item--" Value="0" />
            </asp:DropDownList>
        </ContentTemplate>
    </asp:UpdatePanel>

First, I would like to clarify something. 首先,我想澄清一些事情。 Is this a post back (trip back to server) never occur, or is it the post back occurs, but it never gets into the ddlCountry_SelectedIndexChanged event handler? 这是一个回发(回到服务器)永远不会发生,或者回发后发生,但它永远不会进入ddlCountry_SelectedIndexChanged事件处理程序?

I am not sure which case you are having, but if it is the second case, I can offer some suggestion. 我不确定你遇到了哪种情况,但如果是第二种情况,我可以提出一些建议。 If it is the first case, then the following is FYI. 如果是第一种情况,那么以下是FYI。

For the second case (event handler never fires even though request made), you may want to try the following suggestions: 对于第二种情况(即使请求发生,事件处理程序也不会触发),您可能需要尝试以下建议:

  1. Query the Request.Params[ddlCountries.UniqueID] and see if it has value. 查询Request.Params [ddlCountries.UniqueID]并查看它是否有值。 If it has, manually fire the event handler. 如果有,则手动触发事件处理程序。
  2. As long as view state is on, only bind the list data when it is not a post back. 只要视图状态处于启用状态,只有在列表数据不是回发时才绑定列表数据。
  3. If view state has to be off, then put the list data bind in OnInit instead of OnLoad. 如果必须关闭视图状态,则将列表数据绑定到OnInit而不是OnLoad。

Beware that when calling Control.DataBind(), view state and post back information would no longer be available from the control. 请注意,在调用Control.DataBind()时,控件将不再提供查看状态和回发信息。 In the case of view state is on, between post back, values of the DropDownList would be kept intact (the list does not to be rebound). 在视图状态为on的情况下,在post back之间,DropDownList的值将保持不变(列表不会被反弹)。 If you issue another DataBind in OnLoad, it would clear out its view state data, and the SelectedIndexChanged event would never be fired. 如果在OnLoad中发出另一个DataBind,它将清除其视图状态数据,并且永远不会触发SelectedIndexChanged事件。

In the case of view state is turned off, you have no choice but to rebind the list every time. 在视图状态关闭的情况下,您别无选择,只能每次重新绑定列表。 When a post back occurs, there are internal ASP.NET calls to populate the value from Request.Params to the appropriate controls, and I suspect happen at the time between OnInit and OnLoad. 发生回发时,有内部ASP.NET调用将值从Request.Params填充到适当的控件,我怀疑发生在OnInit和OnLoad之间。 In this case, restoring the list values in OnInit will enable the system to fire events correctly. 在这种情况下,在OnInit中恢复列表值将使系统能够正确触发事件。

Thanks for your time reading this, and welcome everyone to correct if I am wrong. 感谢您抽出时间阅读本文,如果我错了,欢迎大家纠正。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET / C#:DropDownList SelectedIndexChanged事件未触发 - ASP.NET / C#: DropDownList SelectedIndexChanged event not firing ASP.NET MVC C#-DropDownList SelectedIndexChanged不触发 - Asp.net MVC C# - DropDownList SelectedIndexChanged not firing ASP.NET/C# SelectedIndexChanged无法启动 - ASP.NET/C# SelectedIndexChanged not firing on 嵌套的ASP.NET DropDownList SelectedIndexChanged未触发 - Nested ASP.NET DropDownList SelectedIndexChanged Not Firing 更改了selectedIndex的ASP.NET可搜索下拉列表服务器控件 - ASP.NET searchable dropdownlist server control with selectedindexchanged ASP.NET中DropDownList的SelectedIndexChanged以错误的顺序触发 - SelectedIndexChanged for DropDownList in ASP.NET firing in the wrong order dropDownList的SelectedIndexChanged事件没有触发c# - SelectedIndexChanged event of dropDownList not firing c# asp.net c#在从服务器端代码更改索引时阻止触发selectedindexchanged事件 - asp.net c# prevent firing selectedindexchanged event while changing index from serverside code ASP.NET DropDownList未在SelectedIndexChanged上绑定SQL - ASP.NET DropDownList not binding SQL on SelectedIndexChanged ASP.NET 下拉列表 selectedIndexChanged 没有被触发 - ASP.NET dropdownlist selectedIndexChanged not getting triggered
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM