为了实现您的目标,将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 方法编码为字符串。