我有一个与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中的选定值。
我怎么能解决这个问题?
答案 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
方法编码为字符串。