如何在Page_Load方法中获取参数?

时间:2016-01-23 16:33:36

标签: c# asp.net pageload asp.net-controls

我有这个控制权:

<asp:DropDownList ID="ddlPaging" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlPaging_SelectedIndexChanged">
    </asp:DropDownList>

这里我如何将服务器端的数据绑定到上面的控件:

    ddlPaging.Visible = true;
    ddlPaging.DataSource = Enumerable.Range(0, features.Count()).ToList();
    ddlPaging.DataBind();

当我在DropDownList中选择postBack累积并触发此函数时:

        protected void Page_Load(object sender, EventArgs e)
        {
            string controlId= this.FindControl(this.Request.Params.Get("__EVENTTARGET")).ID

        //always empty
        string ctrlarg1 = this.Request.Params.Get("__EVENTARGUMENT");
        string ctrlarg2 = Request.Form["__EVENTARGUMENT"];
        string ctrlarg3 = Request.Params["__EVENTARGUMENT"];
        string ctrlarg4 = this.Request["__EVENTARGUMENT"];
        string ctrlarg5 = this.Request.Params.Get("__EVENTARGUMENT");

        if (!isPaging)
        {
                ddlPaging.Visible = true;
                ddlPaging.DataSource = Enumerable.Range(0, features.Count()).ToList();
                ddlPaging.DataBind();
        }
}

当触发Page_Load方法时,我需要在下拉列表中获取所选项目。

我这样试试:

        string ctrlarg1 = this.Request.Params.Get("__EVENTARGUMENT");
        string ctrlarg2 = Request.Form["__EVENTARGUMENT"];
        string ctrlarg3 = Request.Params["__EVENTARGUMENT"];
        string ctrlarg4 = this.Request["__EVENTARGUMENT"];
        string ctrlarg5 = this.Request.Params.Get("__EVENTARGUMENT");

但结果是空的。

当我以这种方式获得控制ID时:

            string controlId= this.FindControl(this.Request.Params.Get("__EVENTTARGET")).ID

它完美无缺!

所以我的问题是,如何在Page_Load方法的下拉列表中获取所选项?

1 个答案:

答案 0 :(得分:2)

我建议你不要在Page_Load中这样做。 DropDownList类上有一个SelectedIndexChanged事件,恰好就此而言。

<asp:DropDownList runat="server"
                  ID="_ddlMyDdl"
                  AutoPostBack="True"
                  OnSelectedIndexChanged="MyEventHandler"/>

然后在你的代码隐藏中:

protected void MyEventHandler(object sender, EventArgs e)
{
    var selectedId = _ddlMyDdl.SelectedIndex; // or ((DropDownList) sender).SelectedIndex
}
相关问题