Asp.Net统一前后端提示信息方案
目录 |
要解决的问题 |
- 减少弹框前后端代码量
- 增强可维护性
- 前后端提示资源统一
- 可以实现简单的多语言提示方案
- 增强重用性和易用性
...
用自定义XML汇总提示信息 |
- 为了实现前后端提示资源的统一,把提示信息放入自定义XML文件中,初步想法如下(alerttip节点表提示信息节点)
<?xml version="1.0" encoding="utf-8" ?> <tiplist> <alerttip> <id>1</id> <chinese>成功</chinese> </alerttip> <alerttip> <id>-1</id> <chinese>失败</chinese> </alerttip> </tiplist>
- 进一步为了实现简单支持多语言版本和语言设置进一步修改XML结构,修改后如下(增加language节点控制项目语言版本,每个alerttip节点下增加其它语言提示信息)
<?xml version="1.0" encoding="utf-8" ?> <tiplist> <language> <value>chinese</value> </language> <alerttip> <id>1</id> <chinese>成功</chinese> <english>success</english> </alerttip> <alerttip> <id>-1</id> <chinese>失败</chinese> <english>fail</english> </alerttip> </tiplist>
前端弹框实现 |
- Jquery解析XML文件,通过ID节点,返回对应的提示信息
function getTip(tipId) { var returnVal = ""; $.ajax({ url: 'xml/tip.xml', type: 'get', dataType: 'xml', timeout: 1000, cache: true, async: false, error: function(xml) { returnVal = 'Loading Error!'; }, success: function(xml) { var language = $(xml).find('language:first').children("value").text(); $(xml).find("alerttip").each(function(i) { var idVal = $(this).children("id").text(); if (idVal == tipId) { returnVal = $(this).children(language).text(); return false; } }); } }); return returnVal; }
- 提取弹框提示方法
/*------------------------------------------------------------------------------------------- 功能:Windows弹框,通过传入XML文件中ID节点的text查找提示正文 参数:tipId表示XML中ID节点的text ---------------------------------------------------------------------------------------------*/ function alertXml(tipId) { alert(getTip(tipId)); } /*------------------------------------------------------------------------------------------- 功能:Windows弹框,通过传入提示正文 参数:tips表示提示正文 destUrl表示要跳转的目的路径 ---------------------------------------------------------------------------------------------*/ function alertGo(tips, destUrl) { alert(tips); location.href = destUrl; } /*------------------------------------------------------------------------------------------- 功能:Windows弹框,通过传入XML文件中ID节点的text查找提示正文 参数:tipId表示XML中ID节点的text destUrl表示要跳转的目的页面路径 ---------------------------------------------------------------------------------------------*/ function alertGoXml(tipId, destUrl) { alertGo(getTip(tipId), destUrl); }
后端弹框实现 |
- C#解析XML文件,存入Dictionary,并添加XML文件依赖缓存
//提示信息字典
private static Dictionary<string, string> tipDic = null;
#region## 根据ID从XML文件中获取提示信息 /// <summary> /// 根据ID从XML文件中获取提示信息 /// 进行XML文件依赖缓存 /// </summary> /// <param name="filePath">XML提示文件路径</param> /// <param name="tipId">XML文件中ID节点</param> /// <returns>提示信息</returns> private static string GetTipDic(string filePath, string tipId) { string tipStr = string.Empty; if (HttpRuntime.Cache["TipCache"] == null) { tipDic = new Dictionary<string, string>(); string xmlPath = HttpContext.Current.Server.MapPath(filePath); XDocument doc = XDocument.Load(xmlPath); var language = doc.Descendants("language").First().Element("value").Value; var tipList = doc.Descendants("alerttip"); foreach (var item in tipList) { string id = item.Element("id").Value; if (!tipDic.ContainsKey(id)) { tipDic.Add(id, item.Element(language).Value); } } CacheDependency dep = new CacheDependency(xmlPath); HttpRuntime.Cache.Insert("TipCache", tipDic, dep, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration); } else { tipDic = HttpRuntime.Cache["TipCache"] as Dictionary<string, string>; } if (tipDic.ContainsKey(tipId)) { tipStr = tipDic[tipId]; } return tipStr; } #endregion
- 提取弹框方法
//提示XML文件 private const string tipXmlPath = "xml/tip.xml"; #region## Windows弹框 /// <summary> /// 功能:Windows弹框 /// </summary> /// <param name="content">提示正文</param> public static void Alert(string content) { AlertBase(content, null, null); } /// <summary> /// 功能:Windows弹框,从XML中得到提示信息 /// </summary> /// <param name="tipId">XML文件中ID节点值</param> public static void AlertXml(string tipId) { AlertBase(GetTipDic(tipXmlPath, tipId), null, null); } /// <summary> /// 功能:弹框并跳转 /// </summary> /// <param name="content">提示正文</param> /// <param name="url">跳转的URL</param> public static void AlertGo(string content, string url) { AlertBase(content, url, null); } /// <summary> /// 功能:弹框并跳转,从XML中得到提示信息 /// </summary> /// <param name="tipId">XML文件中ID节点值</param> /// <param name="url">跳转的URL</param> public static void AlertGoXml(string tipId, string url) { AlertBase(GetTipDic(tipXmlPath, tipId), url, null); } /// <summary> /// 功能:Windows弹框 /// </summary> /// <param name="alertContext">提示正文</param> /// <param name="url">跳转跳径</param> /// <param name="otherScripts">脚本</param> private static void AlertBase(string alertContext, string url, string otherScripts) { Page page = HttpContext.Current.Handler as Page; System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (!string.IsNullOrEmpty(alertContext)) { sb.AppendFormat("alert(\"{0}\");", alertContext); } if (!string.IsNullOrEmpty(url)) { sb.AppendFormat("location.href=\"{0}\";", url); } if (!string.IsNullOrEmpty(otherScripts)) { sb.AppendFormat("{0};", otherScripts); } page.ClientScript.RegisterStartupScript(page.GetType(), "", sb.ToString(), true); } #endregion
扩展和整合 |
网页为了更好用户体验一般会选择一些JS插件形式的弹出提示,我这里也用扩展一个JQuery弹出插件 jQuery BlockUI Plugin
插件API或DEMO:http://malsup.com/jquery/block/#demos
- 增加前端BlockUI提示并提取各方法到一个JS文件
alert.js 【展开查看详细】/*------------------------------------------------------------------------------------------- 功能:通过XML中的ID节点text返回提示信息 参数:tipId表示XML中ID节点的text ---------------------------------------------------------------------------------------------*/ function getTip(tipId) { var returnVal = ""; $.ajax({ url: 'xml/tip.xml', type: 'get', dataType: 'xml', timeout: 1000, cache: true, async: false, error: function(xml) { returnVal = 'Loading Error!'; }, success: function(xml) { var language = $(xml).find('language:first').children("value").text(); $(xml).find("alerttip").each(function(i) { var idVal = $(this).children("id").text(); if (idVal == tipId) { returnVal = $(this).children(language).text(); return false; } }); } }); return returnVal; } /*------------------------------------------------------------------------------------------- 功能:Windows弹框,通过传入XML文件中ID节点的text查找提示正文 参数:tipId表示XML中ID节点的text ---------------------------------------------------------------------------------------------*/ function alertXml(tipId) { alert(getTip(tipId)); } /*------------------------------------------------------------------------------------------- 功能:Windows弹框,通过传入提示正文 参数:tips表示提示正文 destUrl表示要跳转的目的路径 ---------------------------------------------------------------------------------------------*/ function alertGo(tips, destUrl) { alert(tips); location.href = destUrl; } /*------------------------------------------------------------------------------------------- 功能:Windows弹框,通过传入XML文件中ID节点的text查找提示正文 参数:tipId表示XML中ID节点的text destUrl表示要跳转的目的页面路径 ---------------------------------------------------------------------------------------------*/ function alertGoXml(tipId, destUrl) { alertGo(getTip(tipId), destUrl); } /*------------------------------------------------------------------------------------------- 功能:BlockUI弹框,提示正文直接由参数传入 参数:tips表示提示正文 ---------------------------------------------------------------------------------------------*/ function alertBlockUi(tips) { $.blockUI({ message: '<br/><h1>' + tips + '</h1><br/>', css: { width: '600px' }, timeout: 2000 }); } /*------------------------------------------------------------------------------------------- 功能:BlockUI弹框,通过传入XML文件中ID节点的text查找提示正文 参数:tipId表示XML中ID节点的text ---------------------------------------------------------------------------------------------*/ function alertBlockUiXml(tipId) { alertBlockUi(getTip(tipId)); } /*------------------------------------------------------------------------------------------- 功能:BlockUI弹框并跳转,提示正文直接由参数传入 参数:tips表示提示正文 destUrl表示要跳转的目的页面路径 ---------------------------------------------------------------------------------------------*/ function alertBlockUiGo(tips, destUrl) { $.blockUI({ message: '<br/><h1>' + tips + '</h1><br/>', css: { width: '600px' }, timeout: 2000 }); setTimeout(function() { $.unblockUI({ onUnblock: function() { location.href = destUrl; } }); }, 2000); } /*------------------------------------------------------------------------------------------- 功能:BlockUI弹框并跳转,通过传入XML文件中ID节点的text查找提示正文 参数:tipId表示XML中ID节点的text destUrl表示要跳转的目的页面路径 ---------------------------------------------------------------------------------------------*/ function alertBlockUiGoXml(tipId, destUrl) { alertBlockUiGo(getTip(tipId), destUrl); }
alert.js 函数说明 函数名 说明 getTip(tipId) 方法:
从XML中获取提示信息
参数:
tipId:XML文件中提示信息的对应的ID节点
alertXml(tipId) 方法:
Windows弹框(提示信息从XML中获取)
参数:
tipId:XML文件中提示信息的对应的ID节点
alertGo(tips, destUrl) 方法:
Windows弹框并跳转
参数:
tips:提示正文
destUrl:跳转目的路径
alertGoXml(tipId, destUrl) Windows弹框并跳转提示信息从XML中获取)
参数:
tipId:XML文件中提示信息的对应的ID节点
destUrl:跳转目的路径
alertBlockUi(tips) BlockUI插件弹框
参数:
tips:提示正文
alertBlockUiXml(tipId) BlockUI插件弹框(提示信息从XML中获取)
参数:
tipId:XML文件中提示信息的对应的ID节点
alertBlockUiGo(tips, destUrl) BlockUI插件弹框并跳转
参数:
tips:提示正文
destUrl:跳转目的路径
alertBlockUiGoXml(tipId, destUrl) BlockUI插件弹框并跳转(提示信息从XML中获取)
参数:
tipId:XML文件中提示信息的对应的ID节点
destUrl:跳转目的路径
- 增加后端BlockUI提示并提取各方法到一个.cs文件
AlertHelper.cs 【展开查看详细】using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.Caching; using System.Web.UI; using System.Xml.Linq; namespace Utils { /// <summary> /// 功能: 弹框帮助类 /// 创建人: Wilson /// 时间: 2013-08-07 /// 描述: 添加 System.Web 引用 /// </summary> public class AlertHelper { //提示信息字典 private static Dictionary<string, string> tipDic = null; //提示XML文件 private const string tipXmlPath = "xml/tip.xml"; #region## Windows弹框 /// <summary> /// 功能:Windows弹框 /// </summary> /// <param name="content">提示正文</param> public static void Alert(string content) { AlertBase(content, null, null); } /// <summary> /// 功能:Windows弹框,从XML中得到提示信息 /// </summary> /// <param name="tipId">XML文件中ID节点值</param> public static void AlertXml(string tipId) { AlertBase(GetTipDic(tipXmlPath, tipId), null, null); } /// <summary> /// 功能:弹框并跳转 /// </summary> /// <param name="content">提示正文</param> /// <param name="url">跳转的URL</param> public static void AlertGo(string content, string url) { AlertBase(content, url, null); } /// <summary> /// 功能:弹框并跳转,从XML中得到提示信息 /// </summary> /// <param name="tipId">XML文件中ID节点值</param> /// <param name="url">跳转的URL</param> public static void AlertGoXml(string tipId, string url) { AlertBase(GetTipDic(tipXmlPath, tipId), url, null); } /// <summary> /// 功能:Windows弹框 /// </summary> /// <param name="alertContext">提示正文</param> /// <param name="url">跳转跳径</param> /// <param name="otherScripts">脚本</param> private static void AlertBase(string alertContext, string url, string otherScripts) { Page page = HttpContext.Current.Handler as Page; System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (!string.IsNullOrEmpty(alertContext)) { sb.AppendFormat("alert(\"{0}\");", alertContext); } if (!string.IsNullOrEmpty(url)) { sb.AppendFormat("location.href=\"{0}\";", url); } if (!string.IsNullOrEmpty(otherScripts)) { sb.AppendFormat("{0};", otherScripts); } page.ClientScript.RegisterStartupScript(page.GetType(), "", sb.ToString(), true); } #endregion #region## Jquery弹框 (BlockUI) /// <summary> /// 功能:Jquery插件弹框 /// </summary> /// <param name="alertContext">提示正文</param> public static void JQAlert(string alertContext) { JQAlertBase(alertContext, null); } /// <summary> /// 功能:Jquery插件弹框,从XML中得到提示信息 /// </summary> /// <param name="tipId">XML文件中ID节点值</param> public static void JQAlertXml(string tipId) { JQAlert(GetTipDic(tipXmlPath, tipId)); } /// <summary> /// 功能:Jquery插件弹框并跳转 /// </summary> /// <param name="alertContext">提示正文</param> /// <param name="url">跳转URL</param> public static void JQAlertGo(string alertContext, string url) { JQAlertBase(alertContext, url); } /// <summary> /// 功能:Jquery插件弹框并跳转,从XML中得到提示信息 /// </summary> /// <param name="tipId">XML文件中ID节点值</param> /// <param name="url">跳转URL</param> public static void JQAlertGoXml(string tipId, string url) { JQAlertGo(GetTipDic(tipXmlPath, tipId), url); } /// <summary> /// 功能:Jquery插件弹出 /// </summary> /// <param name="alertContext">提示正文</param> /// <param name="url">跳转URL</param> private static void JQAlertBase(string alertContext, string url) { Page page = HttpContext.Current.Handler as Page; StringBuilder sb = new StringBuilder(); sb.Append("$(function(){{"); if (!string.IsNullOrEmpty(alertContext)) { sb.AppendFormat(@"$.blockUI({{ message: '<br/><h1>{0}</h1><br/>',css: {{ width: ""600px"" }}, timeout: 2000 }});", alertContext); } if (!string.IsNullOrEmpty(url)) { sb.AppendFormat("setTimeout(function() {{ $.unblockUI({{onUnblock: function(){{ location.href='{0}';}} }}); }}, 2000);", url); } sb.Append("}});"); page.ClientScript.RegisterStartupScript(page.GetType(), "", sb.ToString(), true); } #endregion #region## 根据ID从XML文件中获取提示信息 /// <summary> /// 根据ID从XML文件中获取提示信息 /// 进行XML文件依赖缓存 /// </summary> /// <param name="filePath">XML提示文件路径</param> /// <param name="tipId">XML文件中ID节点</param> /// <returns>提示信息</returns> private static string GetTipDic(string filePath, string tipId) { string tipStr = string.Empty; if (HttpRuntime.Cache["TipCache"] == null) { tipDic = new Dictionary<string, string>(); string xmlPath = HttpContext.Current.Server.MapPath(filePath); XDocument doc = XDocument.Load(xmlPath); var language = doc.Descendants("language").First().Element("value").Value; var tipList = doc.Descendants("alerttip"); foreach (var item in tipList) { string id = item.Element("id").Value; if (!tipDic.ContainsKey(id)) { tipDic.Add(id, item.Element(language).Value); } } CacheDependency dep = new CacheDependency(xmlPath); HttpRuntime.Cache.Insert("TipCache", tipDic, dep, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration); } else { tipDic = HttpRuntime.Cache["TipCache"] as Dictionary<string, string>; } if (tipDic.ContainsKey(tipId)) { tipStr = tipDic[tipId]; } return tipStr; } #endregion } }
示例代码(不完整)及截图 |
- 在页面上放置了不同的按钮响应不同的前后端代码
Default.aspx 【展开查看详细】<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AlertTipSamples._Default" %> <!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> <script src="!js/jquery-1.7.2.min.js" type="text/javascript"></script> <script src="!js/jquery.blockUI.js" type="text/javascript"></script> <script src="!js/alert.js" type="text/javascript"></script> <style type="text/css"> h1 { margin: 0; padding: 0; } </style> </head> <body> <form id="form1" runat="server"> <div> <hr /> <input id="btnFrontend" type="button" value="前端提示(Windows)" /> <br /> <br /> <input id="btnFrontendGo" type="button" value="前端提示并跳转(Windows)" /> <br /> <br /> <asp:Button ID="btnbackend" runat="server" Text="后端提示(Windows)" OnClick="btnbackend_Click" /> <br /> <br /> <asp:Button ID="btnbackendGo" runat="server" Text="后端提示并跳转(Windows)" OnClick="btnbackendGo_Click" /> <br /> <br /> <br /> <hr /> <input id="btnJQFrontend" type="button" value="前端提示(Jquery)" /> <br /> <br /> <input id="btnJQFrontendGo" type="button" value="前端提示并跳转(Jquery)" /> <br /> <br /> <asp:Button ID="btnJQbackend" runat="server" Text="后端提示(Jquery)" OnClick="btnJQbackend_Click" /> <br /> <br /> <asp:Button ID="btnJQbackendGo" runat="server" Text="后端提示并跳转(Jquery)" OnClick="btnJQbackendGo_Click" /> <br /> <br /> <br /> <hr /> </div> </form> </body> </html> <script type="text/javascript"> $(function() { $('#btnFrontend').click(function() { alertXml(1); }); $('#btnFrontendGo').click(function() { alertGoXml(1, "Dest.aspx"); }); $('#btnJQFrontend').click(function() { alertBlockUiXml(1); }); $('#btnJQFrontendGo').click(function() { alertBlockUiGoXml(-1, "Dest.aspx"); }); }) </script>
Default.aspx.cs 【展开查看详细】using System; using Utils; namespace AlertTipSamples { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } /// <summary> /// Windows弹框提示 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnbackend_Click(object sender, EventArgs e) { AlertHelper.AlertXml("-1"); } /// <summary> /// Windows弹框提示并跳转 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnbackendGo_Click(object sender, EventArgs e) { AlertHelper.AlertGoXml("-1", "Dest.aspx"); } /// <summary> /// Jquery弹框提示 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnJQbackend_Click(object sender, EventArgs e) { AlertHelper.JQAlertXml("-1"); } /// <summary> /// Jquery弹框提示并跳转 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnJQbackendGo_Click(object sender, EventArgs e) { AlertHelper.JQAlertGoXml("-1", "Dest.aspx"); } } }
示例截图
示例下载 |
示例下载:https://files.cnblogs.com/zhongweiv/AlertTipSamples.zip
示例代码Target Framework为:.NET Framework3.5^_^!
备注:因为是Demo有很多可优化的地方就省略了,XML文件也可以根据提示信息的多少或功能模块决定是否分开放置!
作 者:
Porschev[钟慰]
出 处:
http://www.cnblogs.com/zhongweiv/
微 博:
http://weibo.com/porschev
欢迎任何形式的转载,但请务必注明原文详细链接