无法为分页创建友好的网址

时间:2019-07-24 14:06:38

标签: asp.net-mvc pagination

我需要将网址从g =分页号从/ localhost:9000 /?page = 1更改为/ Products / Page1

               routes.MapRoute(
                     name: "pagination",
                     template: "Products/Page{page}",
                     defaults: new { controller = "Product", action = "List"  
                });
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Product}/{action=List}/{id?}");
 [HtmlTargetElement("div", Attributes = "page-model")]

   public class PageLinkTagHelper:TagHelper

   {

    private IUrlHelperFactory urlHelperFactory;

    public PageLinkTagHelper(IUrlHelperFactory helperFactory)
    {
        this.urlHelperFactory = helperFactory;
    }

    [ViewContext]
    [HtmlAttributeNotBound]
    public ViewContext ViewContext { get; set; }

    public PagingInfo PageModel { get; set; }

    public string PageAction { get; set; }

    public bool PageClassEnabled { get; set; } = false;

    public string PageClass { get; set; }
    public string PageClassNormal { get; set; }
    public string PageClassSelected { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        IUrlHelper urlHelper = this.urlHelperFactory.GetUrlHelper(ViewContext);
        TagBuilder result = new TagBuilder("div");
        for (int i=1;i<=PageModel.TotalPages;i++)
        {
            TagBuilder tag = new TagBuilder("a");
            tag.Attributes["href"] = urlHelper.Action(PageAction, "Product", new { Page = i });
            if(PageClassEnabled)
            {
                tag.AddCssClass(PageClass);
                tag.AddCssClass(i == PageModel.CurrentPage ? PageClassSelected : PageClassNormal);
            }
            tag.InnerHtml.Append(i.ToString());
            result.InnerHtml.AppendHtml(tag);
        }
        output.Content.AppendHtml(result.InnerHtml);
    }
} }
public class ProductController : Controller
{
    private IProductRepository Repository;
    public int PageSize = 4;
    public ProductController(IProductRepository repository)
    {
        this.Repository = repository;
    }

    public ViewResult List(int page = 1)
    {
        //return View(Repository.Products.OrderBy(p=>p.ProductID).Skip((page-1)*PageSize).Take(PageSize));
        return View(new ProductListViewModel
        {
            Products = Repository.Products.OrderBy(p => p.ProductID).Skip((page - 1) * PageSize).Take(PageSize),
            PagingInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = PageSize, TotalItems = Repository.Products.Count()}
        }) ; 
    }

    public IActionResult Index()
    {
        return View();
    }
}

在1.1版中,它可以完美运行,但是现在我在.NET Core 2.1或2.2上工作,看来它无法将页面从路由传递到控制器。 我得到404 Not Found,但网址为/ Products / Page1。有什么建议吗?

0 个答案:

没有答案