生成repeater分页的页码,可以想datagrid一样点击。需要配合PagedDataSource 。
public string CreatePagerLinks(PagedDataSource objPds, string BaseUrl)
{
int totalPageRanger = 3;//set page range is 5, means display five hyperlink for page selection
int pageRanger = (totalPageRanger-1)/2;
StringBuilder sbPager = new StringBuilder();
if (!objPds.IsFirstPage)
{
// first page link
sbPager.Append("<a href=\"");
sbPager.Append(BaseUrl);
sbPager.Append("\">|<</a> ");
if (objPds.CurrentPageIndex != 1)
{
// previous page link
sbPager.Append("<a href=\"");
sbPager.Append(BaseUrl);
sbPager.Append("&page=");
sbPager.Append(objPds.CurrentPageIndex.ToString());
sbPager.Append("\" alt=\"Previous Page\"><<</a> ");
}
}
int intLow = objPds.CurrentPageIndex + 1 - pageRanger;//pageindex + 1 = pagenumber
int intHigh = objPds.CurrentPageIndex + 1 + pageRanger;//pageindex + 1 = pagenumber
if (intLow < 1) intLow = 1;
if (intHigh > objPds.PageCount) intHigh = objPds.PageCount;
if (intHigh - intLow < totalPageRanger)
{
intHigh = intLow + totalPageRanger - 1;
if (intHigh > objPds.PageCount)
intHigh = objPds.PageCount;
}
if (intHigh - intLow < totalPageRanger)
{
intLow = intHigh - totalPageRanger + 1;
if (intLow < 1)
intLow = 1;
}
for (int x = intLow; x <= intHigh ; x++)
{
// numeric links
if (x == objPds.CurrentPageIndex + 1) sbPager.Append(x.ToString() + " ");
else
{
sbPager.Append("<a href=\"");
sbPager.Append(BaseUrl);
sbPager.Append("&page=");
sbPager.Append(x.ToString());
sbPager.Append("\">");
sbPager.Append(x.ToString());
sbPager.Append("</a> " );
}
}
if (!objPds.IsLastPage)
{
if ((objPds.CurrentPageIndex + 2) != objPds.PageCount)
{
// next page link
sbPager.Append("<a href=\"");
sbPager.Append(BaseUrl);
sbPager.Append("&page=");
sbPager.Append(Convert.ToString(objPds.CurrentPageIndex + 2));
sbPager.Append("\">>></a> ");
}
// last page link
sbPager.Append("<a href=\"");
sbPager.Append(BaseUrl);
sbPager.Append("&page=");
sbPager.Append(objPds.PageCount.ToString());
sbPager.Append("\">>|</a>");
}
// conver the final links to a string and assign to labels
return sbPager.ToString();
}
lilPage是一个literal,直接调用上面那个方法赋值就可以。
private void BindRepeater()
{
DataSet ds = new DataSet();
ds = ......
DataTable dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
if (dr["RewardImageUrl"]==null||dr["RewardImageUrl"].ToString().Length ==0)
dr["RewardImageUrl"] = ConfigVar.Get("NO_PIC").ToString();
}
PagedDataSource pagedDataSource = new PagedDataSource();
pagedDataSource.DataSource = ds.Tables[0].DefaultView;
pagedDataSource.AllowPaging = true;
pagedDataSource.PageSize = int.Parse(giftPageSize);
//start paging
if (GetPage() > -1)
{
// subtract 1 because the PagedDataSource uses a zero-based index
int pageIndex = GetPage() - 1 ;
// correct for a page index less than 0 or greater than the last page
if (pageIndex < 0) pageIndex = 0;
if (pageIndex > pagedDataSource.PageCount)
pageIndex = pagedDataSource.PageCount - 1;
pagedDataSource.CurrentPageIndex = pageIndex;
}
this.RepGiftList.DataSource = pagedDataSource;
this.RepGiftList.DataBind();
lilPage.Text = CreatePagerLinks(pagedDataSource, GetAbsolutUri());
}
项目中经常遇到query string的加密解密问题,如果在页面或者page base里面处理的话总有点不爽。
所以最近尝试着用httpmodule解决。在网上看到了几篇文章,综合了一下,解决了postback加密过的url丢失的问题。
HttpModule:
#region Using
using System;
using System.IO;
using System.Web;
using System.Text;
using System.Security.Cryptography;
#endregion
/// <summary>
/// Summary description for QueryStringModule
/// </summary>
public class QueryStringModule : IHttpModule
{
#region IHttpModule Members
public void Dispose()
{
// Nothing to dispose
}
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
#endregion
private const string PARAMETER_NAME = "enc=";
private const string ENCRYPTION_KEY = "key";
void context_BeginRequest(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
if (context.Request.Url.OriginalString.Contains("aspx") && context.Request.RawUrl.Contains("?"))
{
string query = ExtractQuery(context.Request.Url.ToString());
string path = GetVirtualPath();
if (query.StartsWith(PARAMETER_NAME, StringComparison.OrdinalIgnoreCase))
{
// Decrypts the query string and rewrites the path.
context.Items["OriginalUrl"] = context.Request.Url.ToString();
string rawQuery = query.Replace(PARAMETER_NAME, string.Empty);
string decryptedQuery = Decrypt(rawQuery);
context.RewritePath(path, string.Empty, decryptedQuery);
}
else if (context.Request.HttpMethod == "GET")
{
// Encrypt the query string and redirects to the encrypted URL.
// Remove if you don't want all query strings to be encrypted automatically.
string encryptedQuery = Encrypt(query);
context.Items["OriginalUrl"] = path + encryptedQuery;
context.Response.Redirect(path + encryptedQuery);
}
}
}
/// <summary>
/// Parses the current URL and extracts the virtual path without query string.
/// </summary>
/// <returns>The virtual path of the current URL.</returns>
private static string GetVirtualPath()
{
string path = HttpContext.Current.Request.RawUrl;
path = path.Substring(0, path.IndexOf("?"));
path = path.Substring(path.LastIndexOf("/") + 1);
return path;
}
/// <summary>
/// Parses a URL and returns the query string.
/// </summary>
/// <param name="url">The URL to parse.</param>
/// <returns>The query string without the question mark.</returns>
private static string ExtractQuery(string url)
{
int index = url.IndexOf("?") + 1;
return url.Substring(index);
}
#region Encryption/decryption
/// <summary>
/// The salt value used to strengthen the encryption.
/// </summary>
private readonly static byte[] SALT = Encoding.ASCII.GetBytes(ENCRYPTION_KEY.Length.ToString());
/// <summary>
/// Encrypts any string using the Rijndael algorithm.
/// </summary>
/// <param name="inputText">The string to encrypt.</param>
/// <returns>A Base64 encrypted string.</returns>
public static string Encrypt(string inputText)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
byte[] plainText = Encoding.Unicode.GetBytes(inputText);
PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(ENCRYPTION_KEY, SALT);
using (ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16)))
{
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainText, 0, plainText.Length);
cryptoStream.FlushFinalBlock();
return "?" + PARAMETER_NAME + Convert.ToBase64String(memoryStream.ToArray());
}
}
}
}
/// <summary>
/// Decrypts a previously encrypted string.
/// </summary>
/// <param name="inputText">The encrypted string to decrypt.</param>
/// <returns>A decrypted string.</returns>
public static string Decrypt(string inputText)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
byte[] encryptedData = Convert.FromBase64String(inputText);
PasswordDeriveBytes secretKey = new PasswordDeriveBytes(ENCRYPTION_KEY, SALT);
using (ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)))
{
using (MemoryStream memoryStream = new MemoryStream(encryptedData))
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
byte[] plainText = new byte[encryptedData.Length];
int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
return Encoding.Unicode.GetString(plainText, 0, decryptedCount);
}
}
}
}
#endregion
}
PageBase:需要继承一下这个pagebase
public class PageBase:Page
{
protected override void OnLoadComplete(EventArgs e)
{
string originalUrl = Context.Items["OriginalUrl"] as string;
if (!string.IsNullOrEmpty(originalUrl)) //So this page have been urlrewriten, after the page onloaded, rewrite the url of this page to original url
{
string query = string.Empty;
int pos = originalUrl.IndexOf('?');
if (pos >= 0)// check if has query paramet
query = originalUrl.Substring(pos + 1);
// originalUrl = originalUrl.Substring(0, pos);
Context.RewritePath(QueryStringModule.GetVirtualPath(), string.Empty, query);
}
base.OnLoadComplete(e);
}
}
参考
http://msdn.microsoft.com/en-us/library/ms972974.aspx
http://www.webpronews.com/expertarticles/2007/01/25/aspnet-httpmodule-for-query-string-encryption
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class Design_Pattern_Command : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Controller controller = new Controller();
Hello hello = new Hello();
HelloCommand helloCommand = new HelloCommand(hello);
controller.SetCommand(0, helloCommand);
Bye bye = new Bye();
ByeCommand byeCommand = new ByeCommand(bye);
controller.SetCommand(1, byeCommand);
Good good = new Good();
GoodCommand goodCommand = new GoodCommand(good);
controller.SetCommand(2, goodCommand);
controller.OnPush(2);
controller.OnPush(0);
controller.OnPush(1);
}
}
public class Hello
{
public void SayHello()
{
System.Web.HttpContext.Current.Response.Write("Hello!");
}
}
public class Bye
{
public void SayBye()
{
System.Web.HttpContext.Current.Response.Write("Bye!");
}
}
public class Good
{
public void SayGood()
{
System.Web.HttpContext.Current.Response.Write("Good!");
}
}
public interface ICommand
{
void Execute();
}
public class HelloCommand : ICommand
{
private Hello _hello;
public HelloCommand(Hello hello)
{
this._hello = hello;
}
public void Execute()
{
this._hello.SayHello();
}
}
public class ByeCommand : ICommand
{
private Bye _bye;
public ByeCommand(Bye bye)
{
this._bye = bye;
}
public void Execute()
{
this._bye.SayBye();
}
}
public class GoodCommand : ICommand
{
private Good _good;
public GoodCommand(Good good)
{
this._good = good;
}
public void Execute()
{
this._good.SayGood();
}
}
public class Controller
{
ICommand[] commands = new ICommand[3];
public void SetCommand(int slot, ICommand command)
{
commands[slot] = command;
}
public void OnPush(int slot)
{
commands[slot].Execute();
}
}