有的时候想在客户端触发服务器端控件的CLICK事件时我们这么写__doPostBack("id",""),但是为什么有的时候会失效呢?
通过查看客户端源代码发现页面中没有生成__doPostBack()这段JS.
原来ASP.NET要产生__doPostBack的前提是服务器控件要有AutoPostBack = true 并且 控件要启用才行
如果我们没有上面的条件但又想要页面产生__doPostBack怎么办呢?
解决方法:
原来Page里面有个方法是GetPostBackEventReference,这个就可以产生__doPostBack,它有两个版本
1.取得用戶端指令碼函式的參考,(這個參考會) 在叫用時讓伺服器回傳網頁。
public string GetPostBackEventReference(Control);
2.取得用戶端指令碼函式的參考,(這個參考會) 在叫用時讓伺服器回傳網頁。這個方法同時也傳遞參數給在伺服器上執行回傳處理的伺服器控制項。public string GetPostBackEventReference(Control, string);
如果只想产生__doPostBack,则只用第一种就行了,
第二种带参数的,可以通过判断所带入的参数做不同的动作,
下面举个例子.
前台页面
有个服务器控件
<
asp:Button
id
="Button1"
runat
="server"
Text
="Button"
></
asp:Button
>
一个客户端控件用来触发服务器端
<
a
href
="#"
onclick
="document.getElementById('Button1').click()"
>
触发服务器端按钮事件
</
a
>
(2)
利用GetPostBackEventReference给客户端生成__doPostBack()
前台
<
a
href
="#"
onclick
="<%=PostBack()%>"
>
触发服务器端按钮事件
</
a
>
后台
protected
string
PostBack()
{
return this.Page.GetPostBackEventReference(this.Button1,"haha");
}
通过__EVENTARGUMENT="haha"可以判断是不是点了那个链接的PostBack
把Button1的按钮事件这么写:
if
(Request[
"
__EVENTARGUMENT
"
]
==
"
haha
"
)
{
Response.Write("这个是链接的PostBack");
}
else
{
Response.Write("这个不是链接的PostBack");
}
以下这个是微软MSDN上的例子,看起来也不错
public
class
MyControl : Control, IPostBackEventHandler
{
//
Create an integer property that is displayed when
//
the page that contains this control is requested
//
and save it to the control's ViewState property.
public
int
Number
{
get
{
if
( ViewState[
"
Number
"
]
!=
null
)
return
(
int
) ViewState[
"
Number
"
];
return
50
;
}
set
{
ViewState[
"
Number
"
]
=
value;
}
}
//
Implement the RaisePostBackEvent method from the
//
IPostBackEventHandler interface. If 'inc' is passed
//
to this method, it increases the Number property by one.
//
If 'dec' is passed to this method, it decreases the
//
Number property by one.
public
void
RaisePostBackEvent(
string
eventArgument)
{
if
( eventArgument
==
"
inc
"
)
Number
=
Number
+
1
;
if
( eventArgument
==
"
dec
"
)
Number
=
Number
-
1
;
}
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name
=
"
FullTrust
"
)]
protected
override
void
Render(HtmlTextWriter writer)
{
//
Converts the Number property to a string and
//
writes it to the containing page.
writer.Write(
"
The Number is
"
+
Number.ToString()
+
"
(
"
);
//
Uses the GetPostBackEventReference method to pass
//
'inc' to the RaisePostBackEvent method when the link
//
this code creates is clicked.
writer.Write(
"
<a href=\
"
javascript:
"
+ Page.GetPostBackEventReference(this,
"
inc
"
) +
"
\
"
>Increase Number</a>
"
);
writer.Write(
"
or
"
);
//
Uses the GetPostBackEventReference method to pass
//
'dec' to the RaisePostBackEvent method when the link
//
this code creates is clicked.
writer.Write(
"
<a href=\
"
javascript:
"
+ Page.GetPostBackEventReference(this,
"
dec
"
) +
"
\
"
>Decrease Number</a>
"
);
}
}