当前位置:编程学习 > asp >>

Asp.net MVC 3实例学习之ExtShop(四)——完成产品列表页

  在完成产品列表页前要做一些准备功夫。首先是去下载MvcPager用了为产品列表分页。下载的可能是基于MVC 2的,没关系,可以用在MVC 3上。如果有担心,下载源代码重新编译一次好了。下载后将DLL添加到引用里。

      接着是要修改一下路由以实现“Catalog/List/[id]/[page]”的访问。打开“Global.asax.cs”文件,然后在默认路由之前添加以下代码:

1                           routes . MapRoute ( 
2                                   " Catalog " ,   //   Route   name 
3                                   " Catalog/List/{id}/{page} " ,   //   URL   with   parameters 
4                                   new   {   controller   =   " Catalog " ,   action   =   " List " ,   page   =   1   }   //   Parameter   defaults 
5                           ) ; 
6    

     现在打开CatalogController.cs文件,在文件头添加对MvcPager的引用,代码如下:

1   using   Webdiyer . WebControls . Mvc; 

       然后修改Index操作的代码如下:

1                   public   ActionResult   Index ( int?   id ) 
2                   { 
3                           PagedList < T_Products >   q   =   dc . T_Products . OrderByDescending ( m   = >   m . CreateTime ) . ToPagedList ( id   ??   1 ,   8 ) ; 
4                           return   View ( q ) ; 
5                   } 
6    

      代码传入的id是页码而不是产品分类编码,这个要注意。因为要使用分页,所以传递给视图的是PagedList对象,而不是Queryable,这也是要注意的地方。因而,查询结果需要通过toPagedList方法将Queryable对象转换为PagedList对象。第1个参数是当前页面,如果id为空,则默认为第1页。第2个参数是每页显示的产品数量,在这里是8个。

      在“Index”上单击鼠标右键,选择“添加视图”( ,今天换了中文版,菜单也变了)。在视图中添加以下代码:

1   @ using   Webdiyer . WebControls . Mvc ; 
2   @ model   PagedList < Extshop . Models . T_Products > 
3    
4   @ { 
5           ViewBag . Title   =   " 产品列表 " ; 
6           PageData [ " id " ]   =   " " ; 
7   } 
8           < div   class = " nav " > 
9                   < a   href = " @Url.Action( " " ,   " Catalog " ) " > 产品 < / a > 
10           < / div > < br   / > 
11           < div   id = " contentMain "   style = " width:760px; " > 
12                   < span   class = " header "     style = " width:750px; " > 产品列表 < / span > 
13                           @ { 
14                                   foreach ( var   c   in   Model ) 
15                                   { 
16                                           < ul > 
17                                           < li > < a   href = @ Url . Action ( " Details " ,   " Product " ,   new   {   id   =   c . ProductID   } ) > < img   src = / Images / products / @ c . SamllImageUrl    alt = " @c.Title "   / > < / a > < / li > 
18                                           < li   class = title > < a   href = @ Url . Action ( " Details " ,   " Product " ,   new   {   id   =   c . ProductID   } ) > @ c . Title < / a > < / li > 
19                                           < li > 市场价: < del > @ c . MarketPrice . ToString ( " C " ) < / del > < / li > 
20                                           < li > 当前价: @ c . UnitPrice . ToString ( " C " ) < / li > 
21                             &

补充:Web开发 , ASP.Net ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,