主攻ASP.NET.4.5.1 MVC5.0之重生:根据产品类别显示菜单分类和分页_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > 主攻ASP.NET.4.5.1 MVC5.0之重生:根据产品类别显示菜单分类和分页

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

 2014/5/9 10:08:52  小念头  博客园  我要评论(0)
  • 摘要:路径访问的几种方式和分页效果显示其它类别的效果和多数据分页效果默认访问网站路径效果和多数据分页效果URL路径访问可页面http://localhost:5339/stationeryhttp://localhost:5339/stationery/Page2http://localhost:5339/?category=fashionhttp://localhost:5339/?category=stationery主要还是看代码和书
  • 标签:.net ASP.NET MVC net 菜单

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

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

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

 


class="Apple-interchange-newline" />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

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

 

作者:Mark Fan (小念头)    来源:http://cube.cnblogs.com
说明:未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。如有疑问,可以通过 ffgign@qq.com 联系作者,本文章采用 知识共享署名-非商业性使用-相同方式共享 2.5 中国大陆许可协议进行许可

 

知识共享许可协议

 

发表评论
用户名: 匿名