以往在前端網頁中,利用javascript產生的資料想送回後端,交由後端程式處理時,會利用一個隱藏欄位+一個隱藏按鈕(display:'none'),將資料寫入到隱藏欄位中後,再利用javascript去觸發隱藏按鈕,去執行button_click中的程式,如以下寫法:
<script src="jquery-1.4.4.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#Button1').click(function() {
var txtdiv = $('#mydiv').text();
$('#<%=TextBox1.ClientID %>').val(txtdiv);
})
})
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="mydiv">andy</div>
<asp:TextBox ID="TextBox1" runat="server" style="display:none"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="測試按鈕" onclick="Button1_Click" />
</form>
</body>
</html>
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("hello " + TextBox1.Text);
}
今發現有另一個作法,則是利用.Net所產生的__doPostBack(),把資料傳回後端,後端再去實作IPostBackEventHandler介面的RaisePostBackEvent Event,如此也能作到想要的情境。以下為示範程式碼:
Jascript:(若不想手動寫__doPostBack function,拉一個LinkButton,style設"display:none"也能自動產生)
<script src="jquery-1.4.4.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#mybtn').click(function(){
var pageId = '<%= Page.ClientID %>';
__doPostBack(pageId, $('#mydiv').text());
})
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
})
</script>
HTML :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<div id="mydiv">andy</div>
<input type="button" id="mybtn" value="測試按鈕"" />
</form>
</body>
</html>
Default.aspx(C#) :
public partial class Default : System.Web.UI.Page,IPostBackEventHandler
{
public void RaisePostBackEvent(string eventArgument)
{
DoSomeThing(eventArgument);
}
public void DoSomeThing(string name)
{
Response.Write("hello "+name);
}
}
Default.aspx(VB) :
Partial Class Default
Inherits System.Web.UI.Page
Implements IPostBackEventHandler
Private Overloads Sub RaisePostBackEvent(eventArgument As String) Implements IPostBackEventHandler.RaisePostBackEvent
Response.Write("hello " + eventArgument)
End Sub
End Class