主攻ASP.NET.4.5.1 MVC5.0之重生:根据产品类别显示菜单分类和分页

路径访问的几种方式和分页效果

显示其它类别的效果和多数据分页效果

默认访问网站路径效果和多数据分页效果

 


URL路径访问可页面

http://localhost:5339/stationery

http://localhost:5339/stationery/Page2

http://localhost:5339/?category=fashion

http://localhost:5339/?category=stationery

 

主要还是看代码和书,写出来的代码

主要使用这个路径显示和分页的效果

主要还是根据类别生成菜单显示的方法比较实用,请关注下面代码

关注路由配置

测试数据和数据库表

添加ProductsListViewModel.cs 编写如下代码

namespace Toad.WebUI.Models
{
    public class ProductsListViewModel
    {

        public IEnumerable<Products> Products { get; set; }
        public PagingInfo PagingInfo { get; set; }
        public string CurrentCategory { get; set; }
    }
}

 

 ProductController代码

namespace Toad.WebUI.Controllers
{
    public class ProductController : Controller
    {
        private IProductRepository repository;
        public int PageSize = 4;

        public ProductController(IProductRepository productRepository)
        {
            this.repository = productRepository;
        }



        public ViewResult List(string category, int page = 1)
        {

            ProductsListViewModel viewModel = new ProductsListViewModel
            {
                Products = repository.Products
                    .Where(p => category == null || p.Category == category)
                    .OrderBy(p => p.ProductID)
                    .Skip((page - 1) * PageSize)
                    .Take(PageSize),
                PagingInfo = new PagingInfo
                {
                    CurrentPage = page,
                    ItemsPerPage = PageSize,
                    TotalItems = category == null ?
                        repository.Products.Count() :
                        repository.Products.Where(e => e.Category == category).Count()
                },
                CurrentCategory = category
            };
            return View(viewModel);
        }



        ////
        //// GET: /Product/
        //public ActionResult List()
        //{
        //    return View(repository.Products);
        //}
    }
}

 

路由配置代码

namespace Toad.WebUI
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(null,
                         "",
                         new
                         {
                             controller = "Product",
                             action = "List",
                             category = UrlParameter.Optional,
                             page = UrlParameter.Optional
                         }
                     );

            routes.MapRoute(null,
                "Page{page}",
                new { controller = "Product", action = "List", category = (string)null },
                new { page = @"\d+" }
            );

            routes.MapRoute(null,
                "{category}",
                new { controller = "Product", action = "List", page = 1 }
            );

            routes.MapRoute(null,
                "{category}/Page{page}",
                new { controller = "Product", action = "List" },
                new { page = @"\d+" }
            );

            routes.MapRoute(null, "{controller}/{action}");
           

            //routes.MapRoute(
            //    name: "Default",
            //    url: "{controller}/{action}/{id}",
            //    defaults: new { controller = "Product", action = "List", id = UrlParameter.Optional }
            //);



        }
    }
}

HtmlHelpers/PagingHelpers.cs分页代码

namespace Toad.WebUI.HtmlHelpers
{
    public static class PagingHelpers
    {
        public static MvcHtmlString PageLinks(this HtmlHelper html,
                                              PagingInfo pagingInfo,
                                              Func<int, string> pageUrl)
        {

            StringBuilder result = new StringBuilder();
            for (int i = 1; i <= pagingInfo.TotalPages; i++)
            {
                TagBuilder tag = new TagBuilder("a");
                tag.MergeAttribute("href", pageUrl(i));
                tag.InnerHtml = i.ToString();
                if (i == pagingInfo.CurrentPage)
                {
                    tag.AddCssClass("selected");
                    tag.AddCssClass("btn-primary");
                }
                tag.AddCssClass("btn btn-default");
                result.Append(tag.ToString());
            }
            return MvcHtmlString.Create(result.ToString());
        }
    }
}

Models\PagingInfo.cs代码

namespace Toad.WebUI.Models
{
    public class PagingInfo
    {
        public int TotalItems { get; set; }
        public int ItemsPerPage { get; set; }
        public int CurrentPage { get; set; }

        public int TotalPages
        {
            get { return (int)Math.Ceiling((decimal)TotalItems / ItemsPerPage); }
        }
    }
}

NavController.cs代码

namespace Toad.WebUI.Controllers
{
    public class NavController : Controller
    {
        private IProductRepository repository;

        public NavController(IProductRepository repo)
        {
            repository = repo;
        }

        public PartialViewResult Menu(string category = null)
        {

            ViewBag.SelectedCategory = category;

            IEnumerable<string> categories = repository.Products
                                    .Select(x => x.Category)
                                    .Distinct()
                                    .OrderBy(x => x);

            return PartialView(categories);
        }
    }
}

视图部分Shared

Menu.cshtml

@model IEnumerable<string>

@Html.ActionLink("Home", "List", "Product", null,
    new { @class = "btn btn-block btn-default btn-lg" })

@foreach (var link in Model)
{
    @Html.RouteLink(link, new
{
    controller = "Product",
    action = "List",
    category = link,
    page = 1
}, new
{
    @class = "btn btn-block btn-default btn-lg"
        + (link == ViewBag.SelectedCategory ? " btn-primary" : "")
})
}

 

 

Product视图部分

List.cshtml

@using Toad.WebUI.HtmlHelpers
@model Toad.WebUI.Models.ProductsListViewModel

@{
    ViewBag.Title = "Products";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


@foreach (var p in Model.Products)
{
    @Html.Partial("ProductSummary", p)
}

<div class="btn-group pull-right">
    @Html.PageLinks(Model.PagingInfo, x => Url.Action("List",
        new { page = x, category = Model.CurrentCategory }))
</div>

 

 

 

视图部分Shared

 

ProductSummary.cshtml

@model Toad.Domain.EFDB.Products

<div class="well">
    <h3>
        <strong>@Model.Name</strong>
        <span class="pull-right label label-primary">@Model.Price.ToString("c")</span>
    </h3>

    @using (Html.BeginForm("AddToCart", "Cart"))
    {
        <div class="pull-right">
            @Html.HiddenFor(x => x.ProductID)
            @Html.Hidden("returnUrl", Request.Url.PathAndQuery)
            <input type="submit" class="btn btn-success" value="购买" />
        </div>
    }

    <span class="lead"> @Model.Description</span>
</div>

 

 

_Layout.cshtml

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <link href="~/Content/css/site.min.css" rel="stylesheet" />

    <title>@ViewBag.Title</title>
</head>
<body>
    <div class="row">
        <div class="col-md-12">
            @Html.Action("Menu", "Nav")
        </div>
    </div>
        <div>
            @RenderBody()
        </div>
</body>
</html>

 

代码下载链接: http://pan.baidu.com/s/1eQgjZnO 密码: vdnr

声明:本博客高度重视知识产权保护,发现本博客发布的信息包含有侵犯其著作权的链接内容时,请联系我,我将第一时间做相应处理,联系邮箱[email protected]

 

 

 

主攻ASP.NET.4.5.1 MVC5.0之重生:根据产品类别显示菜单分类和分页,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。