【问题标题】:how to send dropdownlist selectedvalue as postback argument in ASP.NET如何在 ASP.NET 中将下拉列表选定值作为回发参数发送
【发布时间】:2013-04-14 21:10:27
【问题描述】:

我有一个与IPostBackEventHandler 配合使用的服务器控件。

在那个控件里面,我有一个 DropDownList。

并且这个 DropDownList 应该使用它的参数引发回发事件。

DropDownList _ddl = new DropDownList();
_ddl.Attributes.Add(HtmlTextWriterAttribute.Onchange.ToString()
    , this.Page.ClientScript.GetPostBackEventReference(this, "this.value"));

我要做的是在回发时获取 DropDownList 的选定值。

public void RaisePostBackEvent(string eventArgument)
{
}

当我从 RaisePostBackEvents 收到时,我只得到“this.value”。不是从 DropDownList 中选择的值。

我该如何解决这个问题?

【问题讨论】:

    标签: asp.net drop-down-menu


    【解决方案1】:

    为了实现您的目标,将ID 分配给_ddl 并将其作为参数传递给GetPostBackEventReference

    DropDownList _ddl = new DropDownList();
    _ddl.ID = "MyDropDownList";
    _ddl.Attributes.Add(HtmlTextWriterAttribute.Onchange.ToString()
        , this.Page.ClientScript.GetPostBackEventReference(this, _ddl.ID));
    

    然后在RaisePostBackEvent 中,您需要通过eventArgument 中提供的ID 找到您的控件,并通过这种方式获得SelectedValue

    public void RaisePostBackEvent(string eventArgument)
    {
        DropDownList _ddl = FindControl(eventArgument) as DropDownList;
        if (_ddl == null) return;
    
        string selectedValue = _ddl.SelectedValue;
        // do whatever you need with value
    }
    

    为什么不能使用 JavaScript this.value?不支持 JavaScript 调用,如果您查看生成的 HTML,您会看到:

    __doPostBack('ctl02','MyDropDownList');
    

    __doPostBack 函数如下:

    function __doPostBack(eventTarget, eventArgument) {
        if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
            theForm.__EVENTTARGET.value = eventTarget;
            theForm.__EVENTARGUMENT.value = eventArgument;
            theForm.submit();
        }
    }
    

    如您所见,recipient 参数等于ctl02,即用户控件的UniqueID。当您在 GetPostBackEventReference 通话中通过 this 时,它就到了。 eventArgument 值被分配给__EVENTARGUMENT 隐藏字段,然后与表单一起提交。这是GetPostBackEventReference 调用的第二个参数。

    所以GetPostBackEventReference 的第二个参数总是被内部类System.Web.UI.Util.QuoteJScriptString 方法编码为字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多