在ASP.NET AJAX中處理表單提交,通常需要遵循以下步驟:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<!-- 在這里放置需要更新的內容 -->
</ContentTemplate>
</asp:UpdatePanel>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="提交" OnClick="Button1_Click" />
</form>
protected void Button1_Click(object sender, EventArgs e)
{
// 獲取表單中的數據
string textBoxValue = TextBox1.Text;
// 執行相應的操作(如驗證、插入數據庫等)
// 更新UpdatePanel內的內容
UpdatePanel1.Update();
}
<script type="text/javascript">
function Button1_Click(sender, e) {
e.preventDefault(); // 阻止表單的默認提交行為
var textBoxValue = document.getElementById('<%= TextBox1.ClientID %>').value;
// 使用XMLHttpRequest對象發送異步請求
var xhr = new XMLHttpRequest();
xhr.open('POST', 'YourPage.aspx/Button1_Click', true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// 處理服務器返回的數據
var response = JSON.parse(xhr.responseText);
}
};
xhr.send(JSON.stringify({ textBoxValue: textBoxValue }));
}
</script>
這樣,當用戶點擊提交按鈕時,表單將使用異步請求發送數據到服務器,服務器端代碼將處理數據并更新UpdatePanel內的內容,而無需刷新整個頁面。