学了那么久ASP.NET一直没有学习__doPsotBack 现在补上,扫扫盲
ASPX页面有包含asp:LinkButton或者带有AutoPostBack属性且其值为true的服务器控件时,ASP.NET会自动为页面生成下面的脚本:
<
input type
=
"
hidden
"
name
=
"
__EVENTTARGET
"
id
=
"
__EVENTTARGET
"
value
=
""
/>
<
input type
=
"
hidden
"
name
=
"
__EVENTARGUMENT
"
id
=
"
__EVENTARGUMENT
"
value
=
""
/>
function __doPostBack(eventTarget, eventArgument) {
if
(
!
theForm.onsubmit
||
(theForm.onsubmit()
!=
false
)) {
theForm.__EVENTTARGET.value
=
eventTarget;
theForm.__EVENTARGUMENT.value
=
eventArgument;
theForm.submit();
}
}
__doPostBack带有两个参数:eventTarget和eventArgument。
eventTarget是引起回送的控件的ID,eventArgument是回调参数(与控件相关的附加数据)。这两个参数分别由隐藏的两个表单域__ EVENTTARGET和__ EVENTARGUMENT保存。
使用这两个隐藏的表单可以查找引起页面回送的控件ID和回送时的参数:
protected
void
Page_Load(
object
sender, EventArgs e)
{
string
target
=
Request.Params[
"
__EVENTTARGET
"
];
string
args
=
Request.Params[
"
__EVENTARGUMENT
"
];
}
因为asp:Button和asp:ImageButton不是使用__doPostBack回送页面,所以使用这两个控件回送页面时,上面的代码是无效的。
使用HTML控件回送页面:
<
form id
=
"
form1
"
runat
=
"
server
"
>
<
asp:LinkButton ID
=
"
LinkButton1
"
runat
=
"
server
"
></
asp:LinkButton
>
<
input type
=
"
button
"
value
=
"
Client Control
"
onclick
=
"
javascript:__doPostBack(’Button1’, ’Button Click’);
"
/>
</
form
>
protected
void
Page_Load(
object
sender, EventArgs e)
{
if
(
this
.IsPostBack)
{
string
target
=
Request.Params[
"
__EVENTTARGET
"
];
string
args
=
Request.Params[
"
__EVENTARGUMENT
"
];
Response.Write(
"
Button ID:
"
+
target
+
"
<br />
"
);
Response.Write(
"
Arguments:
"
+
args
+
"
<br />
"
);
}
}
加入的目的是为了让ASPX自动生成__doPostBack脚本。
阻止asp:Button提交页面:
Code
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
protected void Page_Load(object sender, EventArgs e)
{
string scr = "return confirm(’Are you sure you want to submit this form?’);";
this.Button1.Attributes.Add("onclick", scr);
}