C#输出JS代码封装类-Alart

C#后台输出JS代码我们通常是

Response.Write("<script>js代码</script>");

这样写非常不方便,因此去年10月份的时候特意写了一个封装类,共享在CSDN上,博文地址为http://blog.csdn.net/wenjie315130552/article/details/6934777

code:

 1  /// <summary>
2 /// Alart 的摘要说明
3 /// </summary>
4 public class Alart
5 {
6 public enum AlartState
7 {
8 /// <summary>
9 /// 在根窗口中打开该连接
10 /// </summary>
11 OpenInTopWindow,
12 /// <summary>
13 /// 在父窗口中打开该连接
14 /// </summary>
15 OpenInParentWindow,
16 /// <summary>
17 /// 在当前窗口中打开该连接
18 /// </summary>
19 OpenInThisWindow,
20 /// <summary>
21 /// 返回到上一个页面
22 /// </summary>
23 Back,
24 /// <summary>
25 /// 关闭窗口
26 /// </summary>
27 CloseWindow,
28 /// <summary>
29 /// 不做任何操作
30 /// </summary>
31 Nothing
32 }
33
34 /// <summary>
35 /// 输出JS提示信息对话框
36 /// </summary>
37 /// <param name="context">页面Context</param>HttpContext.Current
38 /// <param name="msg">消息内容</param>
39 /// <param name="alartState">输出模式*枚举</param>
40 /// <param name="toUrl">提示后要转到的URL</param>
41 public static void ShowAlart(HttpContext context, string msg, AlartState alartState,string toUrl)
42 {
43 StringBuilder mySB = new StringBuilder();
44 mySB.AppendFormat("<script language='javascript'>alert('{0}');", msg);
45 switch (alartState)
46 {
47 case AlartState.Back:
48 mySB.Append("history.go(-1)");
49 break;
50 case AlartState.CloseWindow:
51 mySB.Append("top.window.close()");
52 break;
53 case AlartState.OpenInParentWindow:
54 mySB.AppendFormat("parent.location='{0}'",toUrl);
55 break;
56 case AlartState.OpenInThisWindow:
57 mySB.AppendFormat("window.locaiton='{0}'", toUrl);
58 break;
59 case AlartState.OpenInTopWindow:
60 mySB.AppendFormat("top.location='{0}'", toUrl);
61 break;
62 case AlartState.Nothing:
63 break;
64 }
65 mySB.Append("</script>");
66 context.Response.Write(mySB);
67 context.Response.End();
68 }
69
70 /// <summary>
71 /// 输出JS
72 /// </summary>
73 /// <param name="context">页面Context</param>HttpContext.Current
74 /// <param name="jsStr">脚本</param>
75 public static void UseJs(HttpContext context,string jsStr)
76 {
77 StringBuilder mySB = new StringBuilder();
78 mySB.AppendFormat("<script language='javascript'>{0}", jsStr);
79 mySB.Append("</script>");
80 context.Response.End();
81 }
82 }

 

调用:

样式一(返回上一个页面):

 

 Alart.ShowAlart(System.Web.HttpContext.Current, "密码与确认密码不一致", Alart.AlartState.Back, "");

样式二(在本窗口打开):

asp.net mvc:

Alart.ShowAlart(System.Web.HttpContext.Current, "操作成功", Alart.AlartState.OpenInThisWindow, Url.RouteUrl(new { controller = "ControllerName", action = "ActionName"}));

关于如何使用Url.RouteUrl(object routeValues)请参照wtq的博文使用Url.Routeurl获取url值。

asp.net:

 Alart.ShowAlart(System.Web.HttpContext.Current, "操作成功", Alart.AlartState.OpenInThisWindow,"PageName"));

在asp.net中 尽量用 ClientScript.RegisterStartup() 或者 clientScript.RegisterBlock 类似的这样方法,因为Response.Write()直接输出在页面上,会导致页面变形。
 


 

posted @ 2012-03-23 11:13  tofight  阅读(3550)  评论(23编辑  收藏  举报