【发布时间】:2012-03-09 05:01:22
【问题描述】:
我有一个带有提交按钮的 ASP.NET 页面。当我单击该按钮时,我的代码将运行,然后页面重新加载/刷新......整个页面被回发。
我必须使用什么或做什么来防止页面重新加载?阿贾克斯?这将如何实现?
代码示例会很棒!
【问题讨论】:
-
请看一下这个关于ajax更新面板的链接ajax.net-tutorials.com/controls/updatepanel-control
我有一个带有提交按钮的 ASP.NET 页面。当我单击该按钮时,我的代码将运行,然后页面重新加载/刷新......整个页面被回发。
我必须使用什么或做什么来防止页面重新加载?阿贾克斯?这将如何实现?
代码示例会很棒!
【问题讨论】:
如果您想避免您的代码再次运行 你可以在你的 page_load 事件中做
If(!page.IsPostBack())
{
your code here
}
和 ajax 以避免在 jquery 中重新加载 with the example here
或者用asp ajax面板
【讨论】:
如果您不希望页面重新加载,您应该查看 UpdatePanel 控件:http://msdn.microsoft.com/en-us/library/system.web.ui.updatepanel.aspx
【讨论】:
使用 AJAX 的案例 1
在此我们添加了以下控件
1. Script Manager
2. Ajax Update Panel with Trigger and Content Template
3. Button
在这种情况下,您会注意到在单击按钮时,Update Panel 之外的控件将不会更新。这意味着Update Panel 中的控件将在单击按钮时更新。这意味着完整的页面不会被刷新。我希望这能满足您的要求....
输出
更新面板外的日期不会更新,而更新面板内的日期只会更新,因为它在更新面板内,所以不会刷新整个页面。
源代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%=DateTime.Now %>
<br />
<asp:ScriptManager ID="scr" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="Upd" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<%=DateTime.Now %>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btn" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="btn" runat="server" Text="Click Me" />
</div>
</form>
</body>
</html>
没有 AJAX 的情况 2
以下情况也会更新日期,但是由于没有Update Panel,这个时间页面将完全刷新
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%=DateTime.Now %>
<asp:Button ID="btn" runat="server" Text="Click Me" />
</div>
</form>
</body>
</html>
希望本文能帮助您快速了解基础知识
【讨论】: