如何在httpPost ActionResult上进行分页

时间:2017-06-30 17:50:21

标签: asp.net-mvc pagination

我对mvc很新,我遇到了从搜索结果中分页列表的问题。以下是我到目前为止所尝试的内容:这是搜索业务逻辑:

  public IQueryable<IGrouping<int, LLATTRDATA>> GetDocuments(DocumentSearchInputModel searchInputModel)
        {
            try
            {
                _entities = new Entities();
                Logger.Info("connection to db successfull" + _entities);
            }
            catch (Exception e)
            {
              Logger.Error(e);
            }

            if (_entities != null)
            {

                var result = _entities.LLATTRDATAs.AsQueryable();

                //Group Ids together
                var ids = _entities.LLATTRDATAs.Where(r => r.VALSTR.Contains(searchInputModel.OwnersName) && r.ATTRID == 2)
                .Select(r => r.ID);
                Logger.Debug("the Ids are "+ids);

                var selected = _entities.LLATTRDATAs.Where(r => ids.Contains(r.ID)).GroupBy(r => r.ID);
                Logger.Debug("the selected Ids are "+ selected);


                if (searchInputModel != null)
                {
                    //result =
                    foreach (var selectedId in selected)
                    {
                        foreach (var item in selectedId)
                        {
                            item.DATAID = (
                               from l
                                   in _entities.LLATTRDATAs
                               join d
                                   in _entities.DTREEs
                                   on l.ID
                                   equals d.DATAID
                               join v
                                   in _entities.DVERSDATAs
                                   on d.VERSIONNUM
                                   equals v.VERSION
                               where d.DATAID == v.DOCID && l.ATTRID == 2
                                     && l.VALSTR.Contains(searchInputModel.OwnersName) && l.VERNUM == v.VERSION
                               select l.ID).ToList().FirstOrDefault();

                            Logger.Info("DataID is "+ item.DATAID);

                            PROVIDERDATA providerData = (
                                from p
                                    in _entities.PROVIDERDATAs
                                join v
                                    in _entities.DVERSDATAs on p.PROVIDERID
                                    equals v.PROVIDERID
                                where v.DOCID == item.DATAID && v.VERSION == 1
                                select p).FirstOrDefault();
                            Logger.Info("provider data is "+ providerData);

                            //Get the needed string from the full path
                            Regex regexForUsefulUrl = new Regex("(?<==')(.*)(?=','st)", RegexOptions.Singleline);
                            if (providerData != null)
                            {
                                var getUsefulUrl = regexForUsefulUrl.Matches(providerData.PROVIDERDATA1);
                                var useFulUrl = getUsefulUrl[0].Value;
                                Logger.Debug("Needed URL is:", new Exception(useFulUrl));
                                item.FILECONTENT = System.Configuration.ConfigurationManager.AppSettings["ServerUrl"] + useFulUrl;
                            }
                        }
                    }

                   // if (getFileUrl != null) searchInputModel.FileUrl = getFileUrl.providerType;
                }
                Logger.Info($"Results found {result}");

                return selected;
            }
            return null;
        }

现在这是搜索控制器:

 public ActionResult Index()
    {
        if (Request.QueryString != null && Request.QueryString.Count > 0)
        {
            return View();
        }
        return null;

    }

    [HttpPost]
    [HandleError]
    public ActionResult Index(DocumentSearchInputModel searchInputModel, int page = 0)
    {
        _entities = new Entities();
        const int pageSize = 2;

        var business = new SearchBusinessLogic();
        var model = business.GetDocuments(searchInputModel);

        var count = model.Count();

        var data = model.OrderBy(i => i.Key).Skip(page * pageSize).Take(pageSize).ToList();
        //TempData["data"] = data;

        TempData["data"] = data;
        Session.Add("data", data);

        ViewBag.MaxPage = (count / pageSize) - (count % pageSize == 0 ? 1 : 0);

        ViewBag.Page = page;


        //save user search inputs to the db
        using (var db = new LagosOnlineESearchEntities())
        {
            var pin = TempData["UserPin"];
            var result = db.UserSearchInformations.SingleOrDefault(b => b.ReceiptNumber == (string)pin);
            if (result != null)
            {
                if (searchInputModel != null)
                {
                    try
                    {
                     result.SearchByOwnersName = searchInputModel.OwnersName;
                                            result.SearchByOwnersAddress = searchInputModel.OwnersAddress;
                                            result.SearchByVolumeNumber = searchInputModel.VolumeNumber;
                                            result.SearchBySurveyPlanNumber = searchInputModel.SurveyPlanNumber;
                                            result.SearchByDescriptionOrLocationOfProperty = searchInputModel.DescriptionOrLocationOfProp;
                    }
                    catch (Exception e)
                    {

                        Logger.Error("Error", e);
                    }

                }
                Logger.Info("Details about to be to save");
                db.SaveChanges();
                Logger.Info("User search inputs saved to the db");
            }
        }
        if (!ModelState.IsValid) {

            return View(searchInputModel);
        }
        return View("searchResult", data);

    }

注意:HttpGet索引显示搜索输入字段(它是多搜索)

这是我的观点(我遇到问题的部分):

 @if (ViewBag.Page > 0)
                {
                    <a href="@Url.Action("Index", "Search", new {page = ViewBag.Page  - 1})" class="btn btn-danger btn-fill">&laquo; PREV</a>
                }

                @if (ViewBag.Page < ViewBag.MaxPage)
                {
                    <a href="@Url.Action("Index", "Search", new {page = ViewBag.Page  + 1})" class="btn btn-danger btn-fill">NEXT &laquo;</a>
                }

因此,如果单击“下一步”,则会转到httpGet搜索索引(搜索输入页面),而不是剩余的搜索结果。请问我该怎么做才能做到这一点?

由于

我刚刚找到另一条可能的解决方案,通过添加一个新的actionResult方法并将httpPost索引中的所有代码移动到这个方法,如下所示:

 [HttpGet]
    public ActionResult SearchResult(int page = 0)
    {
        DocumentSearchInputModel searchInputModel = (DocumentSearchInputModel) TempData["data"];

        _entities = new Entities();
        const int pageSize = 2;

        var business = new SearchBusinessLogic();
        var model = business.GetDocuments(searchInputModel);

        var count = model.Count();

        var data = model.OrderBy(i => i.Key).Skip(page * pageSize).Take(pageSize).ToList();

        ViewBag.MaxPage = (count / pageSize) - (count % pageSize == 0 ? 1 : 0);

        ViewBag.Page = page;

        return View("searchResult", data);
    }

但是searchInputModel返回null而不是用户输入,我尝试过tempData,viewbag和viewdata,似乎没有工作。所以我现在的挑战是如何将用户输入从索引httppost传递给新的actionresult方法。谢谢你们......

1 个答案:

答案 0 :(得分:0)

要回答这个问题:“但是searchInputModel返回null而不是用户输入,我已经尝试过tempData,viewbag和viewdata,似乎没有工作。”这只是因为您在调用请求之前尚未将其值设置为TempData,ViewBag或ViewData。

所以,我的建议是将get和set代码添加到此部分:

    @if (ViewBag.Page > 0)
        {
            //To get and set user inputs here
            var searchInputModel = new DocumentSearchInputModel();
            ...
            TempData["data"] = searchInputModel;
            <a href="@Url.Action("Index", "Search", new {page = ViewBag.Page  - 1})" class="btn btn-danger btn-fill">&laquo; PREV</a>
        }

@if (ViewBag.Page < ViewBag.MaxPage)
        {
           //To get and set user inputs here
            var searchInputModel = new DocumentSearchInputModel();
            ...
            TempData["data"] = searchInputModel;
            <a href="@Url.Action("Index", "Search", new {page = ViewBag.Page  + 1})" class="btn btn-danger btn-fill">NEXT &laquo;</a>
        }

但是,在编写此分页之前,我认为您最好先查看一些教程。例如,这个非常好且易于理解:https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application