如何在ASP.NET MVC上将搜索结果打印为pdf?

问题描述

我是ASP.NET MVC的新手,我正在尝试将两个日期之间的过滤记录打印为PDF。我正在使用ROTATIVA生成PDF,问题是PDF正确生成了,但是包含所有记录,不仅包含两个日期之前的记录过滤器的结果。

控制器代码

    //this method is for put the list of the records on the view
    public ActionResult SaleList()
    {
        using (inventoryEntitiesDBA dc = new inventoryEntitiesDBA())
        {
            return View(dc.sales.ToList());
        }
    }

    //this method is to filter the records between start and end date
    [HttpPost]
    public ActionResult SaleList(DateTime start,DateTime end)
    {
        bool Status = false;
        if(ModelStatus.IsValid())
        {
            using(inventoryEntitiesDBA dc = new inventoryEntitiesDBA())
            {
                 var d = dc.sales.Where(x => x.sale_day >= start && x.sale_day <= end).ToList();
              
                 Status = true;

                 ViewBag.Status = Status;

                 return View(d);
            }
        } 
    }

    //this method is to generate the PDF
    public ActionResult SalesToPdf()
    {
        var report = new ActionAsPdf("SaleList");

        return report;
    }

我不知道该怎么做,任何建议都会受到赞赏。

* UPDATE ---> view

@if (ViewBag.Status != null && Convert.ToBoolean(ViewBag.Status))
{
    //this is for print if the method for filter
    //the dates are called
    <p align="right">
         @Html.ActionLink("Generate PDF","SalesToPdf2")
    </p>
}
else
{
    //this is for print if the method for filter the dates are not called
    <p align="right">
         @Html.ActionLink("Generate PDF","SalesToPdf")
    </p>
}

<center>
    @using (Html.BeginForm("SaleList","Sales",FormMethod.Post))
    {
        
        <span>Start Date </span> <input type="date" name="start" />
        <span> End Date </span><input type="date" name="end" />
        <input type="submit" value="Filter" />
    }
</center>

解决方法

您正在调用没有参数的SalesToPdf动作,这意味着它将始终与未过滤的列表匹配。您可以将参数传递到ActionAsPdf重载中,如文档here

所示

对于您而言,这可能需要对过滤后的列表采取某种单独的操作,如下所示:

    [HttpPost]
    public ActionResult SalesToPdf(DateTime startDate,DateTime endDate)
    {
        var report = new ActionAsPdf("SaleList",new {start=startDate,end=endDate});

        return report;
    }

因此,如果您有未过滤的数据,则可以调用现有操作,而对于已过滤的数据,则可以调用此操作。