JScript .NETXHTMLQA.NET 1.0Visual Studio .NET 2003WebFormsVisual Studio 2008.NET 1.1.NET 3.0Visual Studio 2005ADO.NETASP设计 / 图形架构师.NET4高级.NET 2.0CSS.NET 3.5AjaxC# 2.0C# 3.0PHPHTMLC# 4.0中级开发Visual StudioJavascript.NETASP.NETC#
ASP.NET 页面中耗时任务的简单“正在进行”消息






4.55/5 (7投票s)
使用 JavaScript 在 ASP.NET 页面中显示“正在进行”消息并禁用控件
引言
我们经常会遇到当用户单击按钮控件时,需要较长时间来执行任务的网页。在延迟期间,用户通常会倾向于单击页面的其他选项——这会导致意外的行为和奇怪的页面结果。当您的网页在服务器端任务上花费数秒钟时,显示“正在进行”消息总是明智的。还有其他复杂的方法可以使用 Ajax .NET 控件来实现相同的功能,如“Modal Popup Extender”、模态窗口、iframe 等。
我的解决方案是一个简单的 JavaScript,它速度快、轻量级,并且不会干扰您的 ASP.NET 服务器端代码。对于 PHP、JSP、Cold Fusion 等其他 Web 编程语言,它也应该能正常工作。
场景
我有一个 ASPX 页面,它在单击按钮时检索数据并绑定到 ASP.NET Grid。此过程需要 30 秒才能显示结果,在此期间页面必须
- 显示“正在进行”消息(带有一个 GIF 图像以获得动画效果)
- 在显示“正在进行”消息时限制用户访问其他控件,以避免不必要的后回发。
解决方案
- 将一个
div
标签添加到 HTML 代码中,以显示消息和图像。将div
标签的可见性设置为hidden
。<div id=""ProcessingWindow"" visible=""false""> <img src="%22loading.gif%22" /> </div>
- JavaScript 函数
ShowProcessMessage()
将Div
设置为‘visible
’,并将进度消息和图像添加到Div
标签的innerHTML
中。
注意:包含 GIF 图像以显示图像以获得动画效果。<script language ="javascript" type="text/javascript" > ShowProcessMessage = function(PanelName) { //Sets the visibility of the Div to 'visible' document.getElementById(PanelName).style.visibility = "visible"; /* Displays the 'In-Process' message through the innerHTML. You can write Image Tag to display Animated Gif */ document.getElementById(PanelName).innerHTML = 'In-Process...Please Wait ... '; //Call Function to Disable all the other Controls DisableAllControls ('btnLoad'); return true; //Returns the control to the Server click event } </script>
- JavaScript 函数
DisableAllControls()
用于禁用除引发事件的控件以及隐藏类型(ASP.NET 事件处理程序和 Viewstate)之外的所有控件。<script language ="javascript" type="text/javascript" > DisableAllControls = function(CtrlName) { var elm; /*Loop for all the controls of the page.*/ for(i = 0; i <= document.forms[0].elements.length -1 ; i++) { /* 1.Check for the Controls with type 'hidden' – which are ASP.NET hidden controls for Viewstate and EventHandlers. It is very important that these are always enabled, for ASP.NET page to be working. 2.Also Check for the control which raised the event (Button) - It should be active. */ elm = document.forms[0].elements[i]; if( (elm.name == CtrlName) || (elm.type =='hidden') ) { elm.disabled=false; } else { elm.disabled=true; //Disables all the other controls } } } </script>
- 在
Button
的OnClientClick
事件上调用 JavaScript 函数。页面控件首先命中客户端函数,然后转到服务器端事件处理程序。<asp:Button ID="btnLoad" runat="server" onclick="btnLoad_Click" Text="Get Songs List" OnClientClick ="ShowProcessMessage('ProcessingWindow')" />
结束语
这是我们在开发更大功能的网页时大多数人都会遇到的一个常见问题。对于 PHP、JSP、Cold Fusion 等其他 Web 编程语言,它也应该能正常工作。
希望这个解决方案能有所帮助。
编程愉快!
历史
- 2009 年 7 月 4 日:首次发布