与分页的模型绑定

时间:2018-04-30 19:34:47

标签: c# asp.net-core model-binding

我有一个PagingInfo类,用于将信息传递给控制器​​以获取分页功能:

        public int TotalItems { get; set; }
        public int ItemsPerPage { get; set; }
        public int CurrentPage { get; set; }

        public int TotalPages => (int)Math.Ceiling((decimal)TotalItems / ItemsPerPage);

分页按钮通过以下方式呈现在我的视图中:

<div page-model="Model.PagingInfo" page-action="SearchResult" page-classes-enabled="true" page-class="btn" page-class-selected="btn-primary" class="btn-group pull-right m-1"></div>

因为它包含自定义标记助手:

[HtmlTargetElement("div", Attributes = "page-model")]
    public class PageLinkTagHelper : TagHelper
    {
        private IUrlHelperFactory urlHelperFactory;

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

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

        public PagingInfo PageModel { get; set; }

        public string PageAction { get; set; }

        public bool PageClassesEnabled { 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 = 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,
                   new { listPage = i });
                if (PageClassesEnabled)
                {
                    tag.AddCssClass(PageClass);
                    tag.AddCssClass(i == PageModel.CurrentPage
                        ? PageClassSelected : PageClassNormal);
                }
                tag.InnerHtml.Append(i.ToString());
                result.InnerHtml.AppendHtml(tag);
            }
            output.Content.AppendHtml(result.InnerHtml);
        }
    }

同样在我的视图中,我绑定了筛选为分页显示的项目所需的特定模型元素,例如

<input hidden asp-for="@Model.SearchTerms.FormID" class="form-control" />

这全部包含在<form>标记中。但是,当我单击分页按钮时,不会发生模型绑定。

如果我改为将<div>标记更改为<button>标记,我就可以进行模型绑定,如下所示:

<button page-model="Model.PagingInfo" page-action="SearchResult" page-classes-enabled="true" page-class="btn" page-class-selected="btn-primary" class="btn-group pull-right m-1"></button>

然而,这会弄乱分页按钮显示使其无法使用(<a>标签也是如此)。有没有办法在<div>元素中绑定我的模型?

0 个答案:

没有答案