【C#公共帮助类】 WebHelper帮助类

如果你是一个新手,如果你刚接触MVC,如果你跟着置顶的那个项目,我们肯定会用到这里面的几个帮助类

它们都在Common类库下,大家一定要记住要点:取其精华去其糟粕,切勿拿来主义~

 

ApplicationCache.cs

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Web;
 6 
 7 namespace Common
 8 {
 9     public interface ICache
10     {
11         /// <summary>
12         /// 获取全局应用缓存
13         /// </summary>
14         /// <param name="key"></param>
15         /// <returns></returns>
16         object GetApplicationCache(string key);
17         /// <summary>
18         /// 设置全局应用缓存
19         /// </summary>
20         /// <param name="key"></param>
21         /// <param name="obj"></param>
22         void SetApplicationCache(string key, object obj);
23         /// <summary>
24         /// 删除全局应用缓存
25         /// </summary>
26         /// <param name="key"></param>
27         void RemoveApplicationCache(string key);
28     }
29     /// <summary>
30     /// 全局应用缓存
31     /// </summary>
32     public  class ApplicationCache:ICache
33     {
34         #region ICache 成员
35 
36         public object GetApplicationCache(string key)
37         {
38             return HttpContext.Current.Application[key];
39         }
40 
41         public void SetApplicationCache(string key, object obj)
42         {
43             HttpContext.Current.Application.Add(key, obj);
44         }
45 
46         public void RemoveApplicationCache(string key)
47         {
48             HttpContext.Current.Application.Remove(key);
49         }
50         #endregion
51     }
52 }
View Code

 

 

 

BindDataControl.cs

 

 1 using System.Web.UI.WebControls;
 2 using System.Web.UI;
 3 using System.Data;
 4 using System.Data.SqlClient;
 5 
 6 namespace Common
 7 {
 8     /// <summary>
 9     /// 数据展示控件 绑定数据类
10     /// </summary>
11     public class BindDataControl
12     {
13         #region 绑定服务器数据控件 简单绑定DataList
14         /// <summary>
15         /// 简单绑定DataList
16         /// </summary>
17         /// <param name="ctrl">控件ID</param>
18         /// <param name="mydv">数据视图</param>
19         public static void BindDataList(Control ctrl, DataView mydv)
20         {
21             ((DataList)ctrl).DataSourceID = null;
22             ((DataList)ctrl).DataSource = mydv;
23             ((DataList)ctrl).DataBind();
24         }
25         #endregion
26 
27         #region 绑定服务器数据控件 SqlDataReader简单绑定DataList
28         /// <summary>
29         /// SqlDataReader简单绑定DataList
30         /// </summary>
31         /// <param name="ctrl">控件ID</param>
32         /// <param name="mydv">数据视图</param>
33         public static void BindDataReaderList(Control ctrl, SqlDataReader mydv)
34         {
35             ((DataList)ctrl).DataSourceID = null;
36             ((DataList)ctrl).DataSource = mydv;
37             ((DataList)ctrl).DataBind();
38         }
39         #endregion
40 
41         #region 绑定服务器数据控件 简单绑定GridView
42         /// <summary>
43         /// 简单绑定GridView
44         /// </summary>
45         /// <param name="ctrl">控件ID</param>
46         /// <param name="mydv">数据视图</param>
47         public static void BindGridView(Control ctrl, DataView mydv)
48         {
49             ((GridView)ctrl).DataSourceID = null;
50             ((GridView)ctrl).DataSource = mydv;
51             ((GridView)ctrl).DataBind();
52         }
53         #endregion
54 
55         /// <summary>
56         /// 绑定服务器控件 简单绑定Repeater
57         /// </summary>
58         /// <param name="ctrl">控件ID</param>
59         /// <param name="mydv">数据视图</param>
60         public static void BindRepeater(Control ctrl, DataView mydv)
61         {
62             ((Repeater)ctrl).DataSourceID = null;
63             ((Repeater)ctrl).DataSource = mydv;
64             ((Repeater)ctrl).DataBind();
65         }
66     }
67 }
View Code

 

 

 

CacheHelper.cs

 

 1 using System;
 2 using System.Web;
 3 using System.Collections;
 4 
 5 namespace Common
 6 {
 7     /// <summary>
 8     /// 缓存辅助类
 9     /// </summary>
10     public class CacheHelper
11     {
12         /// <summary>
13         /// 获取数据缓存
14         /// </summary>
15         /// <param name="CacheKey"></param>
16         public static object GetCache(string CacheKey)
17         {
18             System.Web.Caching.Cache objCache = HttpRuntime.Cache;
19             return objCache[CacheKey];
20         }
21 
22         /// <summary>
23         /// 设置数据缓存
24         /// </summary>
25         public static void SetCache(string CacheKey, object objObject)
26         {
27             System.Web.Caching.Cache objCache = HttpRuntime.Cache;
28             objCache.Insert(CacheKey, objObject);
29         }
30 
31         /// <summary>
32         /// 设置数据缓存
33         /// </summary>
34         public static void SetCache(string CacheKey, object objObject, TimeSpan Timeout)
35         {
36             System.Web.Caching.Cache objCache = HttpRuntime.Cache;
37             objCache.Insert(CacheKey, objObject, null, DateTime.MaxValue, Timeout, System.Web.Caching.CacheItemPriority.NotRemovable, null);
38         }
39 
40         /// <summary>
41         /// 设置数据缓存
42         /// </summary>
43         public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
44         {
45             System.Web.Caching.Cache objCache = HttpRuntime.Cache;
46             objCache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);
47         }
48 
49         /// <summary>
50         /// 移除指定数据缓存
51         /// </summary>
52         public static void RemoveAllCache(string CacheKey)
53         {
54             System.Web.Caching.Cache _cache = HttpRuntime.Cache;
55             _cache.Remove(CacheKey);
56         }
57 
58         /// <summary>
59         /// 移除全部缓存
60         /// </summary>
61         public static void RemoveAllCache()
62         {
63             System.Web.Caching.Cache _cache = HttpRuntime.Cache;
64             IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
65             while (CacheEnum.MoveNext())
66             {
67                 _cache.Remove(CacheEnum.Key.ToString());
68             }
69         }
70     }
71 }
View Code

 

 

 

CookieHelper.cs

 

 1 using System;
 2 using System.Web;
 3 
 4 namespace Common
 5 {
 6     /// <summary>
 7     /// Cookie辅助类
 8     /// </summary>
 9     public class CookieHelper
10     {
11         /// <summary>
12         /// 清除指定Cookie
13         /// </summary>
14         /// <param name="cookiename">cookiename</param>
15         public static void ClearCookie(string cookiename)
16         {
17             HttpCookie cookie = HttpContext.Current.Request.Cookies[cookiename];
18             if (cookie != null)
19             {
20                 TimeSpan ts = new TimeSpan(-1, 0, 0, 0);
21                 cookie.Expires = DateTime.Now.Add(ts);
22                 HttpContext.Current.Response.AppendCookie(cookie);
23                 HttpContext.Current.Request.Cookies.Remove(cookiename);
24             }
25         }
26         /// <summary>
27         /// 获取指定Cookie值
28         /// </summary>
29         /// <param name="cookiename">cookiename</param>
30         /// <returns></returns>
31         public static string GetCookieValue(string cookiename)
32         {
33             HttpCookie cookie = HttpContext.Current.Request.Cookies[cookiename];
34             string str = string.Empty;
35             if (cookie != null)
36             {
37                 str = cookie.Value;
38             }
39             return str;
40         }
41         /// <summary>
42         /// 获取cookie
43         /// </summary>
44         /// <param name="cookiename"></param>
45         /// <returns></returns>
46         public static HttpCookie GetCookie(string cookiename)
47         {
48             return HttpContext.Current.Request.Cookies[cookiename];
49         }
50         /// <summary>
51         /// 添加一个Cookie,默认浏览器关闭过期
52         /// </summary>
53         public static void SetCookie(string cookiename, System.Collections.Specialized.NameValueCollection cookievalue, int? days)
54         {
55             var cookie = HttpContext.Current.Request.Cookies[cookiename];
56             if (cookie == null)
57             {
58                 cookie = new HttpCookie(cookiename);
59             }
60             ClearCookie(cookiename);
61             cookie.Values.Add(cookievalue);
62             var siteurl = System.Configuration.ConfigurationManager.AppSettings["siteurl"];
63             if (!string.IsNullOrEmpty(siteurl))
64             {
65                 cookie.Domain = siteurl.Replace("www.", "");
66             }
67             if (days != null && days > 0) { cookie.Expires = DateTime.Now.AddDays(Convert.ToInt32(days)); }
68             HttpContext.Current.Response.AppendCookie(cookie);
69 
70         }
71         /// <summary>
72         /// 添加一个Cookie
73         /// </summary>
74         /// <param name="cookiename">cookie名</param>
75         /// <param name="cookievalue">cookie值</param>
76         /// <param name="expires">过期时间 null为浏览器过期</param>
77         public static void SetCookie(string cookiename, string cookievalue, int? expires)
78         {
79             var cookie = HttpContext.Current.Request.Cookies[cookiename];
80             if (cookie == null)
81             {
82                 cookie = new HttpCookie(cookiename);
83             }
84             ClearCookie(cookiename);
85             cookie = new HttpCookie(cookiename);
86             cookie.Value = cookievalue;
87             var siteurl = System.Configuration.ConfigurationManager.AppSettings["siteurl"];
88             if (!string.IsNullOrEmpty(siteurl))
89             {
90                 cookie.Domain = siteurl.Replace("www.", "");
91             }
92             if (expires != null && expires > 0) { cookie.Expires = DateTime.Now.AddDays(Convert.ToInt32(expires)); }
93             HttpContext.Current.Response.AppendCookie(cookie);
94 
95         }
96     }
97 }
View Code

 

 

 

JScript.cs

 

  1 using System;
  2 using System.Data;
  3 using System.Configuration;
  4 using System.Web;
  5 using System.Web.Security;
  6 using System.Web.UI;
  7 using System.Web.UI.WebControls;
  8 using System.Web.UI.WebControls.WebParts;
  9 using System.Web.UI.HtmlControls;
 10 
 11 namespace Common
 12 {
 13     /// <summary>
 14     /// 一些常用的Js调用
 15     /// 添加新版说明:由于旧版普遍采用Response.Write(string msg)的方式输出js脚本,这种
 16     /// 方式输出的js脚本会在html元素的&lt;html&gt;&lt;/html&gt;标签之外,破坏了整个xhtml的结构,
 17     /// 而新版本则采用ClientScript.RegisterStartupScript(string msg)的方式输出,不会改变xhtml的结构,
 18     /// 不会影响执行效果。
 19     /// 为了向下兼容,所以新版本采用了重载的方式,新版本中要求一个System.Web.UI.Page类的实例。
 20     /// </summary>
 21     public class JScript
 22     {
 23         #region 旧版本
 24         /// <summary>
 25         /// 弹出JavaScript小窗口
 26         /// </summary>
 27         /// <param name="message">窗口信息</param>
 28         public static void Alert(string message)
 29         {
 30             #region
 31             string js = @"<Script language='JavaScript'>
 32                     alert('" + message + "');</Script>";
 33             HttpContext.Current.Response.Write(js);
 34             #endregion
 35         }
 36 
 37         /// <summary>
 38         /// 弹出消息框并且转向到新的URL
 39         /// </summary>
 40         /// <param name="message">消息内容</param>
 41         /// <param name="toURL">连接地址</param>
 42         public static void AlertAndRedirect(string message, string toURL)
 43         {
 44             #region
 45             string js = "<script language=javascript>alert('{0}');window.location.replace('{1}')</script>";
 46             HttpContext.Current.Response.Write(string.Format(js, message, toURL));
 47             #endregion
 48         }
 49 
 50         /// <summary>
 51         /// 回到历史页面
 52         /// </summary>
 53         /// <param name="value">-1/1</param>
 54         public static void GoHistory(int value)
 55         {
 56             #region
 57             string js = @"<Script language='JavaScript'>
 58                     history.go({0});  
 59                   </Script>";
 60             HttpContext.Current.Response.Write(string.Format(js, value));
 61             #endregion
 62         }
 63 
 64         /// <summary>
 65         /// 关闭当前窗口
 66         /// </summary>
 67         public static void CloseWindow()
 68         {
 69             #region
 70             string js = @"<Script language='JavaScript'>
 71                     parent.opener=null;window.close();  
 72                   </Script>";
 73             HttpContext.Current.Response.Write(js);
 74             HttpContext.Current.Response.End();
 75             #endregion
 76         }
 77 
 78         /// <summary>
 79         /// 刷新父窗口
 80         /// </summary>
 81         public static void RefreshParent(string url)
 82         {
 83             #region
 84             string js = @"<Script language='JavaScript'>
 85                     window.opener.location.href='" + url + "';window.close();</Script>";
 86             HttpContext.Current.Response.Write(js);
 87             #endregion
 88         }
 89 
 90 
 91         /// <summary>
 92         /// 刷新打开窗口
 93         /// </summary>
 94         public static void RefreshOpener()
 95         {
 96             #region
 97             string js = @"<Script language='JavaScript'>
 98                     opener.location.reload();
 99                   </Script>";
100             HttpContext.Current.Response.Write(js);
101             #endregion
102         }
103 
104 
105         /// <summary>
106         /// 打开指定大小的新窗体
107         /// </summary>
108         /// <param name="url">地址</param>
109         /// <param name="width"></param>
110         /// <param name="heigth"></param>
111         /// <param name="top">头位置</param>
112         /// <param name="left">左位置</param>
113         public static void OpenWebFormSize(string url, int width, int heigth, int top, int left)
114         {
115             #region
116             string js = @"<Script language='JavaScript'>window.open('" + url + @"','','height=" + heigth + ",width=" + width + ",top=" + top + ",left=" + left + ",location=no,menubar=no,resizable=yes,scrollbars=yes,status=yes,titlebar=no,toolbar=no,directories=no');</Script>";
117 
118             HttpContext.Current.Response.Write(js);
119             #endregion
120         }
121 
122 
123         /// <summary>
124         /// 转向Url制定的页面
125         /// </summary>
126         /// <param name="url">连接地址</param>
127         public static void JavaScriptLocationHref(string url)
128         {
129             #region 转向按钮Js
130             string js = @"<Script language='JavaScript'>
131                     window.location.replace('{0}');
132                   </Script>";
133             js = string.Format(js, url);
134             HttpContext.Current.Response.Write(js);
135             #endregion
136         }
137 
138         /// <summary>
139         /// 打开指定大小位置的模式对话框
140         /// </summary>
141         /// <param name="webFormUrl">连接地址</param>
142         /// <param name="width"></param>
143         /// <param name="height"></param>
144         /// <param name="top">距离上位置</param>
145         /// <param name="left">距离左位置</param>
146         public static void ShowModalDialogWindow(string webFormUrl, int width, int height, int top, int left)
147         {
148             #region 大小位置
149             string features = "dialogWidth:" + width.ToString() + "px"
150                 + ";dialogHeight:" + height.ToString() + "px"
151                 + ";dialogLeft:" + left.ToString() + "px"
152                 + ";dialogTop:" + top.ToString() + "px"
153                 + ";center:yes;help=no;resizable:no;status:no;scroll=yes";
154             ShowModalDialogWindow(webFormUrl, features);
155             #endregion
156         }
157         /// <summary>
158         /// 弹出模态窗口
159         /// </summary>
160         /// <param name="webFormUrl"></param>
161         /// <param name="features"></param>
162         public static void ShowModalDialogWindow(string webFormUrl, string features)
163         {
164             string js = ShowModalDialogJavascript(webFormUrl, features);
165             HttpContext.Current.Response.Write(js);
166         }
167         /// <summary>
168         /// 弹出模态窗口
169         /// </summary>
170         /// <param name="webFormUrl"></param>
171         /// <param name="features"></param>
172         /// <returns></returns>
173         public static string ShowModalDialogJavascript(string webFormUrl, string features)
174         {
175             #region 模态窗口
176             string js = @"<script language=javascript>                            
177                             showModalDialog('" + webFormUrl + "','','" + features + "');</script>";
178             return js;
179             #endregion
180         }
181         #endregion
182 
183         #region 新版本
184         /// <summary>
185         /// 弹出JavaScript小窗口
186         /// </summary>
187         /// <param name="message">窗口信息</param>
188         /// <param name="page">Page类的实例</param>
189         public static void Alert(string message, Page page)
190         {
191             #region
192             string js = @"<Script language='JavaScript'>
193                     alert('" + message + "');</Script>";
194             if (!page.ClientScript.IsStartupScriptRegistered(page.GetType(), "alert"))
195             {
196                 page.ClientScript.RegisterStartupScript(page.GetType(), "alert", js);
197             }
198             #endregion
199         }
200 
201         /// <summary>
202         /// 弹出消息框并且转向到新的URL
203         /// </summary>
204         /// <param name="message">消息内容</param>
205         /// <param name="toURL">连接地址</param>
206         /// <param name="page">Page类的实例</param> 
207         public static void AlertAndRedirect(string message, string toURL, Page page)
208         {
209             #region
210             string js = "<script language=javascript>alert('{0}');window.location.replace('{1}')</script>";
211             if (!page.ClientScript.IsStartupScriptRegistered(page.GetType(), "AlertAndRedirect"))
212             {
213                 page.ClientScript.RegisterStartupScript(page.GetType(), "AlertAndRedirect", string.Format(js, message, toURL));
214             }
215             #endregion
216         }
217 
218         /// <summary>
219         /// 回到历史页面
220         /// </summary>
221         /// <param name="value">-1/1</param>
222         /// <param name="page">Page类的实例</param> 
223         public static void GoHistory(int value, Page page)
224         {
225             #region
226             string js = @"<Script language='JavaScript'>
227                     history.go({0});  
228                   </Script>";
229             if (!page.ClientScript.IsStartupScriptRegistered(page.GetType(), "GoHistory"))
230             {
231                 page.ClientScript.RegisterStartupScript(page.GetType(), "GoHistory", string.Format(js, value));
232             }
233             #endregion
234         }
235 
236         /// <summary>
237         /// 刷新父窗口
238         /// </summary>
239         /// <param name="url">要刷新的url</param>
240         /// <param name="page">Page类的实例</param>
241         public static void RefreshParent(string url, Page page)
242         {
243             #region
244             string js = @"<Script language='JavaScript'>
245                     window.opener.location.href='" + url + "';window.close();</Script>";
246             //HttpContext.Current.Response.Write(js);
247             if (!page.ClientScript.IsStartupScriptRegistered(page.GetType(), "RefreshParent"))
248             {
249                 page.ClientScript.RegisterStartupScript(page.GetType(), "RefreshParent", js);
250             }
251             #endregion
252         }
253 
254 
255         /// <summary>
256         /// 刷新打开窗口
257         /// </summary>
258         /// <param name="page">Page类的实例</param>
259         public static void RefreshOpener(Page page)
260         {
261             #region
262             string js = @"<Script language='JavaScript'>
263                     opener.location.reload();
264                   </Script>";
265             //HttpContext.Current.Response.Write(js);
266             if (!page.ClientScript.IsStartupScriptRegistered(page.GetType(), "RefreshOpener"))
267             {
268                 page.ClientScript.RegisterStartupScript(page.GetType(), "RefreshOpener", js);
269             }
270             #endregion
271         }
272 
273 
274         /// <summary>
275         /// 打开指定大小的新窗体
276         /// </summary>
277         /// <param name="url">地址</param>
278         /// <param name="width"></param>
279         /// <param name="heigth"></param>
280         /// <param name="top">头位置</param>
281         /// <param name="left">左位置</param>
282         /// <param name="page">Page类的实例</param>
283         public static void OpenWebFormSize(string url, int width, int heigth, int top, int left, Page page)
284         {
285             #region
286             string js = @"<Script language='JavaScript'>window.open('" + url + @"','','height=" + heigth + ",width=" + width + ",top=" + top + ",left=" + left + ",location=no,menubar=no,resizable=yes,scrollbars=yes,status=yes,titlebar=no,toolbar=no,directories=no');</Script>";
287             //HttpContext.Current.Response.Write(js);
288             if (!page.ClientScript.IsStartupScriptRegistered(page.GetType(), "OpenWebFormSize"))
289             {
290                 page.ClientScript.RegisterStartupScript(page.GetType(), "OpenWebFormSize", js);
291             }
292             #endregion
293         }
294 
295 
296         /// <summary>
297         /// 转向Url制定的页面
298         /// </summary>
299         /// <param name="url">连接地址</param>
300         /// <param name="page">Page类的实例</param>
301         public static void JavaScriptLocationHref(string url, Page page)
302         {
303             #region
304             string js = @"<Script language='JavaScript'>
305                     window.location.replace('{0}');
306                   </Script>";
307             js = string.Format(js, url);
308             if (!page.ClientScript.IsStartupScriptRegistered(page.GetType(), "JavaScriptLocationHref"))
309             {
310                 page.ClientScript.RegisterStartupScript(page.GetType(), "JavaScriptLocationHref", js);
311             }
312             #endregion
313         }
314 
315         /// <summary>
316         /// 打开指定大小位置的模式对话框
317         /// </summary>
318         /// <param name="webFormUrl">连接地址</param>
319         /// <param name="width"></param>
320         /// <param name="height"></param>
321         /// <param name="top">距离上位置</param>
322         /// <param name="left">距离左位置</param>
323         /// <param name="page">Page类的实例</param>
324         public static void ShowModalDialogWindow(string webFormUrl, int width, int height, int top, int left, Page page)
325         {
326             #region
327             string features = "dialogWidth:" + width.ToString() + "px"
328                 + ";dialogHeight:" + height.ToString() + "px"
329                 + ";dialogLeft:" + left.ToString() + "px"
330                 + ";dialogTop:" + top.ToString() + "px"
331                 + ";center:yes;help=no;resizable:no;status:no;scroll=yes";
332             ShowModalDialogWindow(webFormUrl, features, page);
333             #endregion
334         }
335         /// <summary>
336         /// 弹出模态窗口
337         /// </summary>
338         /// <param name="webFormUrl"></param>
339         /// <param name="features"></param>
340         /// <param name="page">Page类的实例</param>
341         public static void ShowModalDialogWindow(string webFormUrl, string features, Page page)
342         {
343             string js = ShowModalDialogJavascript(webFormUrl, features);
344             if (!page.ClientScript.IsStartupScriptRegistered(page.GetType(), "ShowModalDialogWindow"))
345             {
346                 page.ClientScript.RegisterStartupScript(page.GetType(), "ShowModalDialogWindow", js);
347             }
348         }
349         /// <summary>
350         /// 向当前页面动态输出客户端脚本代码
351         /// </summary>
352         /// <param name="javascript">javascript脚本段</param>
353         /// <param name="page">Page类的实例</param>
354         /// <param name="afterForm">是否紧跟在&lt;form&gt;标记之后输出javascript脚本,如果不是则在&lt;/form&gt;标记之前输出脚本代码</param>
355         public static void AppendScript(string javascript, Page page, bool afterForm)
356         {
357             if (afterForm)
358             {
359                 page.ClientScript.RegisterClientScriptBlock(page.GetType(), page.ToString(), javascript);
360             }
361             else
362             {
363                 page.ClientScript.RegisterStartupScript(page.GetType(), page.ToString(),javascript);
364             }
365         }
366         #endregion
367     }
368 }
View Code

 

 

 

QueryString.cs

 

  1 using System.Web;
  2 using System.Text.RegularExpressions;
  3 
  4 namespace Common
  5 {
  6     /// <summary>
  7     /// QueryString 地址栏参数
  8     /// </summary>
  9     public class QueryString
 10     {
 11         #region 等于Request.QueryString;如果为null 返回 空“” ,否则返回Request.QueryString[name]
 12         /// <summary>
 13         /// 等于Request.QueryString;如果为null 返回 空“” ,否则返回Request.QueryString[name]
 14         /// </summary>
 15         /// <param name="name"></param>
 16         /// <returns></returns>
 17         public static string Q(string name)
 18         {
 19             return Request.QueryString[name] == null ? "" : Request.QueryString[name];
 20         }
 21         #endregion
 22 
 23         /// <summary>
 24         /// 等于  Request.Form  如果为null 返回 空“” ,否则返回 Request.Form[name]
 25         /// </summary>
 26         /// <param name="name"></param>
 27         /// <returns></returns>
 28         public static string FormRequest(string name)
 29         {
 30             return Request.Form[name] == null ? "" : Request.Form[name].ToString();
 31         }
 32         #region 获取url中的id
 33         /// <summary>
 34         /// 获取url中的id
 35         /// </summary>
 36         /// <param name="name"></param>
 37         /// <returns></returns>
 38         public static int QId(string name)
 39         {
 40             return StrToId(Q(name));
 41         }
 42         #endregion
 43 
 44         #region 获取正确的Id,如果不是正整数,返回0
 45         /// <summary>
 46         /// 获取正确的Id,如果不是正整数,返回0
 47         /// </summary>
 48         /// <param name="_value"></param>
 49         /// <returns>返回正确的整数ID,失败返回0</returns>
 50         public static int StrToId(string _value)
 51         {
 52             if (IsNumberId(_value))
 53                 return int.Parse(_value);
 54             else
 55                 return 0;
 56         }
 57         #endregion
 58 
 59         #region 检查一个字符串是否是纯数字构成的,一般用于查询字符串参数的有效性验证。
 60         /// <summary>
 61         /// 检查一个字符串是否是纯数字构成的,一般用于查询字符串参数的有效性验证。
 62         /// </summary>
 63         /// <param name="_value">需验证的字符串。。</param>
 64         /// <returns>是否合法的bool值。</returns>
 65         public static bool IsNumberId(string _value)
 66         {
 67             return QuickValidate("^[1-9]*[0-9]*$", _value);
 68         }
 69         #endregion
 70 
 71         #region 快速验证一个字符串是否符合指定的正则表达式。
 72         /// <summary>
 73         /// 快速验证一个字符串是否符合指定的正则表达式。
 74         /// </summary>
 75         /// <param name="_express">正则表达式的内容。</param>
 76         /// <param name="_value">需验证的字符串。</param>
 77         /// <returns>是否合法的bool值。</returns>
 78         public static bool QuickValidate(string _express, string _value)
 79         {
 80             if (_value == null) return false;
 81             Regex myRegex = new Regex(_express);
 82             if (_value.Length == 0)
 83             {
 84                 return false;
 85             }
 86             return myRegex.IsMatch(_value);
 87         }
 88         #endregion
 89 
 90         #region 类内部调用
 91         /// <summary>
 92         /// HttpContext Current
 93         /// </summary>
 94         public static HttpContext Current
 95         {
 96             get { return HttpContext.Current; }
 97         }
 98         /// <summary>
 99         /// HttpContext Current  HttpRequest Request   get { return Current.Request;
100         /// </summary>
101         public static HttpRequest Request
102         {
103             get { return Current.Request; }
104         }
105         /// <summary>
106         ///  HttpContext Current  HttpRequest Request   get { return Current.Request; HttpResponse Response  return Current.Response;
107         /// </summary>
108         public static HttpResponse Response
109         {
110             get { return Current.Response; }
111         }
112         #endregion
113     }
114 }
View Code

 

 

 

RupengPager.cs

 

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Web;
  5 using System.Text;
  6 using System.Diagnostics;
  7 
  8 namespace Common
  9 {
 10     /// <summary>
 11     /// 分页组件调用实例
 12     /// var pager = new Common.RupengPager();
 13     ///        pager.UrlFormat = "测试分页.aspx?pagenum={n}";//设置分页URL
 14     ///        pager.PageSize = 10; //设置每页显示个数
 15     ///        pager.TryParseCurrentPageIndex(Request["pagenum"]);//获取当前页数
 16     ///        int startRowIndex = (pager.CurrentPageIndex - 1) * pager.PageSize;//开始行号计算
 17     ///        So_KeywordLogBLL bll = new So_KeywordLogBLL();//获取分页数据
 18     ///        pager.TotalCount = bll.GetTotalCount();//计算总个数
 19     ///        Repeater1.DataSource = bll.GetPagedData(startRowIndex, startRowIndex + pager.PageSize - 1); //设置数据绑定
 20     ///        Repeater1.DataBind(); 
 21     ///       PagerHTML = pager.Render();//渲染页码条HTML
 22     /// </summary>
 23     public class RupengPager
 24     {
 25         /// <summary>
 26         /// 总数据条数
 27         /// </summary>
 28         public int TotalCount { get; set; }
 29 
 30         /// <summary>
 31         /// 每页数据条数
 32         /// </summary>
 33         public int PageSize { get; set; }
 34 
 35         /// <summary>
 36         /// 当前页码(从1开始)
 37         /// </summary>
 38         public int CurrentPageIndex { get; set; }
 39 
 40         /// <summary>
 41         /// 显示出来最多的页码数量,因为假设有100页,不可能把100页都显示到界面上
 42         /// </summary>
 43         public int MaxPagerCount { get; set; }
 44 
 45         /// <summary>
 46         /// 页码链接的地址格式,页码用{n}占位。
 47         /// </summary>
 48         public string UrlFormat { get; set; }
 49         /// <summary>
 50         /// 默认初始化
 51         /// </summary>
 52         public RupengPager()
 53         {
 54             PageSize = 10;
 55             MaxPagerCount = 10;
 56         }
 57 
 58         /// <summary>
 59         /// 尝试从字符串pn中解析当前页面赋值给CurrentPageIndex
 60         /// </summary>
 61         /// <param name="pn"></param>
 62         public void TryParseCurrentPageIndex(string pn)
 63         {
 64             int temp;
 65             if (int.TryParse(pn, out temp))
 66             {
 67                 CurrentPageIndex = temp;
 68             }
 69             else
 70             {
 71                 CurrentPageIndex = 1;
 72             }
 73         }
 74 
 75         /// <summary>
 76         /// 创建页码链接
 77         /// </summary>
 78         /// <param name="i">页码</param>
 79         /// <param name="text">链接文本</param>
 80         /// <returns></returns>
 81         private string GetPageLink(int i,string text)
 82         {
 83             StringBuilder sb = new StringBuilder();
 84             string url = UrlFormat.Replace("{n}", i.ToString());
 85             sb.Append("<a href='").Append(url).Append("'>").Append(text).Append("</a>");
 86             return sb.ToString();
 87         }
 88         public string Render()
 89         {
 90          
 91 
 92             StringBuilder sb = new StringBuilder();
 93             //TotalCount=35,PageSize=10,pageCount=4
 94 
 95             //计算总页数,如果是30条,则是3页,31条也是3页,29条也是3页,因此是
 96             //天花板运算Ceiling
 97             double tempCount = TotalCount / PageSize;
 98             int pageCount = (int)Math.Ceiling(tempCount);
 99 
100             //计算显示的页码数(当总页码大于MaxPagerCount)的起始页码
101             int visibleStart = CurrentPageIndex-MaxPagerCount/2;
102             if (visibleStart <1)
103             {
104                 visibleStart = 1;
105             }
106 
107             //计算显示的页码数(当总页码大于MaxPagerCount)的起始页码
108             int visibleEnd = visibleStart + MaxPagerCount;
109             //显示最多MaxPagerCount条
110             //如果算出来的结束页码大于总页码的话则调整为最大页码
111             if (visibleEnd >pageCount)
112             {
113                 visibleEnd = pageCount;
114             }
115 
116             if (CurrentPageIndex > 1)
117             {
118                 sb.Append(GetPageLink(1, "首页"));
119                 sb.Append(GetPageLink(CurrentPageIndex - 1, "上一页"));
120             }
121             else
122             {
123                 sb.Append("<span>首页</span>");
124                 //如果没有上一页了,则只显示一个上一页的文字,没有超链接
125                 sb.Append("<span>上一页</span>");
126             }
127 
128             //绘制可视的页码链接
129             for (int i = visibleStart; i <= visibleEnd; i++)
130             {
131                 //当前页不是超链接
132                 if (i == CurrentPageIndex)
133                 {
134                     sb.Append("<span>").Append(i).Append("</span>");
135                 }
136                 else
137                 {
138                     sb.Append(GetPageLink(i,i.ToString()));
139                 }                
140             }
141             if (CurrentPageIndex < pageCount)
142             {
143                 sb.Append(GetPageLink(CurrentPageIndex + 1, "下一页"));
144                 sb.Append(GetPageLink(pageCount + 1, "末页"));
145             }
146             else
147             {
148                 sb.Append("<span>下一页</span>");
149                 sb.Append("<span>末页</span>");
150             }            
151             return sb.ToString();
152         }
153     }
154 }
View Code

 

 

 

SessionHelper.cs

 

  1 using System.Web;
  2 
  3 namespace Common
  4 {
  5     /// <summary>
  6     /// Session 操作类
  7     /// 1、GetSession(string name)根据session名获取session对象
  8     /// 2、SetSession(string name, object val)设置session
  9     /// </summary>
 10     public class SessionHelper
 11     {
 12         /// <summary>
 13         /// 根据session名获取session对象
 14         /// </summary>
 15         /// <param name="name"></param>
 16         /// <returns></returns>
 17         public static object GetSession(string name)
 18         {
 19             return HttpContext.Current.Session[name];
 20         }
 21         /// <summary>
 22         /// 设置session
 23         /// </summary>
 24         /// <param name="name">session 名</param>
 25         /// <param name="val">session 值</param>
 26         public static void SetSession(string name, object val)
 27         {
 28             HttpContext.Current.Session.Remove(name);
 29             HttpContext.Current.Session.Add(name, val);
 30         }
 31         /// <summary>
 32         /// 添加Session,调动有效期为20分钟
 33         /// </summary>
 34         /// <param name="strSessionName">Session对象名称</param>
 35         /// <param name="strValue">Session值</param>
 36         public static void Add(string strSessionName, string strValue)
 37         {
 38             HttpContext.Current.Session[strSessionName] = strValue;
 39             HttpContext.Current.Session.Timeout = 20;
 40         }
 41 
 42         /// <summary>
 43         /// 添加Session,调动有效期为20分钟
 44         /// </summary>
 45         /// <param name="strSessionName">Session对象名称</param>
 46         /// <param name="strValues">Session值数组</param>
 47         public static void Adds(string strSessionName, string[] strValues)
 48         {
 49             HttpContext.Current.Session[strSessionName] = strValues;
 50             HttpContext.Current.Session.Timeout = 20;
 51         }
 52 
 53         /// <summary>
 54         /// 添加Session
 55         /// </summary>
 56         /// <param name="strSessionName">Session对象名称</param>
 57         /// <param name="strValue">Session值</param>
 58         /// <param name="iExpires">调动有效期(分钟)</param>
 59         public static void Add(string strSessionName, string strValue, int iExpires)
 60         {
 61             HttpContext.Current.Session[strSessionName] = strValue;
 62             HttpContext.Current.Session.Timeout = iExpires;
 63         }
 64 
 65         /// <summary>
 66         /// 添加Session
 67         /// </summary>
 68         /// <param name="strSessionName">Session对象名称</param>
 69         /// <param name="strValues">Session值数组</param>
 70         /// <param name="iExpires">调动有效期(分钟)</param>
 71         public static void Adds(string strSessionName, string[] strValues, int iExpires)
 72         {
 73             HttpContext.Current.Session[strSessionName] = strValues;
 74             HttpContext.Current.Session.Timeout = iExpires;
 75         }
 76 
 77         /// <summary>
 78         /// 读取某个Session对象值
 79         /// </summary>
 80         /// <param name="strSessionName">Session对象名称</param>
 81         /// <returns>Session对象值</returns>
 82         public static string Get(string strSessionName)
 83         {
 84             if (HttpContext.Current.Session[strSessionName] == null)
 85             {
 86                 return null;
 87             }
 88             else
 89             {
 90                 return HttpContext.Current.Session[strSessionName].ToString();
 91             }
 92         }
 93 
 94         /// <summary>
 95         /// 读取某个Session对象值数组
 96         /// </summary>
 97         /// <param name="strSessionName">Session对象名称</param>
 98         /// <returns>Session对象值数组</returns>
 99         public static string[] Gets(string strSessionName)
100         {
101             if (HttpContext.Current.Session[strSessionName] == null)
102             {
103                 return null;
104             }
105             else
106             {
107                 return (string[])HttpContext.Current.Session[strSessionName];
108             }
109         }
110 
111         /// <summary>
112         /// 删除某个Session对象
113         /// </summary>
114         /// <param name="strSessionName">Session对象名称</param>
115         public static void Del(string strSessionName)
116         {
117             HttpContext.Current.Session[strSessionName] = null;
118         }
119         /// <summary>
120         /// 移除Session
121         /// </summary>
122         public static void Remove(string sessionname)
123         {
124             if (HttpContext.Current.Session[sessionname] != null)
125             {
126                 HttpContext.Current.Session.Remove(sessionname);
127                 HttpContext.Current.Session[sessionname] = null;
128             }
129         }
130     }
131 }
View Code

 

 

 

原创文章 转载请尊重劳动成果 http://yuangang.cnblogs.com

 

转载于:https://www.cnblogs.com/yuangang/p/5507953.html

超级多的C#辅助大全 网上有各式各样的帮助公共,但是比较零碎,经常有人再群里或者各种社交账号上问有没有这个helper,那个helper,于是萌生了收集全部helper的念头,以便日后使用。各式各样的几乎都能找到,所有功能性代码都是独立的之间没有联系,可以单独引用至项目。 1. C#读取AD域里用户名或组 2. Chart图形 3. cmd 4. Cookie&Session 5. CSV文件转换 6. DataTable转实体 7. DBHelper 8. DecimalUtility及中文大写数字 9. DLL 10. Excel操作 11. FTP操作 12. H5-微信 13. Html操作 14. INI文件读写 15. IP辅助 16. Javascript 17. Json 18. JSON操作 19. JS操作 20. Lib 21. Mime 22. Net 23. NPOI 24. obj 25. packages 26. Path 27. PDF 28. Properties 29. QueryString 地址栏参数 30. RDLC直接打印帮助 31. ResourceManager 32. RMB 33. SqlHelper 34. SQL语句拦截器 35. URL的操作 36. VerifyCode 37. XML操作 38. 上传下载 39. 二维码操作 40. 共用工具 41. 其他 42. 分词辅助 43. 分页 44. 加密解密 45. 压缩解压缩 46. 各种验证帮助 47. 图片 48. 图片操作 49. 图片验证码 50. 处理多媒体的公共 51. 处理枚举 52. 字符串 53. 对象转换处理 54. 帮助文档 55. 序列化 56. 异步线程 57. 弹出消息 58. 数据展示控件绑定数据 59. 文件操作 60. 日历 61. 日志 62. 时间戳 63. 时间操作 64. 条形码 65. 条形码帮助 66. 条形码转HTML 67. 检测是否有Sql危险字符 68. 正则表达式 69. 汉字转拼音 70. 注册表操作 71. 科学计数,数学 72. 型转换 73. 系统操作相关的公共 74. 缓存 75. 网站安全 76. 网站路径操作 77. 网络 78. 视频帮助 79. 视频转换 80. 计划任务 81. 邮件 82. 邮件2 83. 配置文件操作 84. 阿里云 85. 随机数 86. 页面辅助 87. 验证码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值