在开始之前,您需要一个叫NBuilder的DLL,这个东西可以免除你要先在数据库里面造数据,下载地址http://code.google.com/p/nbuilder/downloads/detail?
name=NBuilder-3.0.1.zip
下面开始我们的工程:
1、在Global.asax下加上
routes.MapRoute("Products", "{controller}/{action}/Page/{page}/Property/{property}/Reverse/{reverse}",
new { controller = "Home", action = "Index", page = 1,property = "Name", reverse = false });
2、准备Product类
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public string Description { get; set; }
public DateTime CreateDate { get; set; }
}
3、新建类ProductRepository,添加NBuilder的引用
public class ProductRepository
{
public List<Product> GetProducts(int page, int recordCount,string sortField, bool reverseSort)
{
List<Product> result = Builder<Product>
.CreateListOfSize(page * recordCount).WhereAll()
.Have(x => x.Description = @"...").Build()
.SortBy(sortField)
.ToList();
//reverse the sort?
if (reverseSort)
result.Reverse();
//do the paging
return result.Skip((page - 1) * recordCount).ToList();
}
}
4、新建类RepositoryHelperscs,扩展IList的SortBy方法(这个对于linq很有用哟)
public static class RepositoryHelperscs
{
private static object GetPropertyValue(object obj,string property)
{
System.Reflection.PropertyInfo propertyInfo =
obj.GetType().GetProperty(property);
return propertyInfo.GetValue(obj, null);
}
public static IList<T> SortBy<T>(this IList<T> list,string property)
{
//order the results
if (!String.IsNullOrEmpty(property))
list = (from item in list.AsEnumerable()
orderby GetPropertyValue(item, property)
select item).ToList();
return list;
}
}
5、在Index视图中加上如下代码
<% List<Product> products = ViewData["Products"] as List<Product>;%>
<%int page = (int) ViewData["page"];%>
<%string property = ViewData["property"].ToString();%>
<% bool reverse = (bool) ViewData["reverse"];%>
<% int PreviousPage = (page - 1) < 1 ? 1 : page - 1;%>
<% int NextPage = page + 1;%>
<%= Html.ActionLink("Previous", "Index", new { @page = PreviousPage, @property = property, @reverse = reverse })%> -
<%= Html.ActionLink("Next", "Index", new { @page = NextPage,@property = property, @reverse = reverse })%>
<%= Html.ActionLink("Sort By Name", "Index", new { @page = page, @property = "Name", @reverse = property == "Name" && reverse ? false : true
})%> |
<%= Html.ActionLink("Sort By Price", "Index", new { @page = page, @property = "Price", @reverse = property == "Price" && reverse ? false : true
})%> |
<%= Html.ActionLink("Sort By Date", "Index", new { @page = page, @property = "CreateDate", @reverse = property == "CreateDate" && reverse ?
false : true })%>
<table>
<tr>
<th>
ProductId
</th>
<th>
Name
</th>
<th>
Price
</th>
<th>
Description
</th>
<th>
CreateDate
</th>
</tr>
<% foreach (Product p in products)
{ %>
<tr>
<td>
<%= p.ProductId %>
</td>
<td>
<%= p.Name %>
</td>
<td>
<%= p.Price %>
</td>
<td>
<%= p.Description %>
</td>
<td>
<%= p.CreateDate %>
</td>
</tr>
<% } %>
</table>
你访问http://localhost:4411/Home/Index/Page/1/Property/name/Reverse/看看,是不是你想要的