如何在ASP.NET中将dropdownlist selectedvalue作为回发参数发送

时间:2013-04-07 08:02:42

标签: asp.net drop-down-menu

我有一个与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中的选定值。

我怎么能解决这个问题?

1 个答案:

答案 0 :(得分: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中,您需要通过ID中提供的eventArgument找到您的控件,并以此方式获取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。当你在this电话中通过GetPostBackEventReference时它就到了。 eventArgument值已分配给__EVENTARGUMENT隐藏字段,然后随表单提交。这是GetPostBackEventReference调用的第二个参数。

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

相关问题