asp.net-mvcpaginationpagedlist

getting the error: String reference not set to an instance of a String


When I filter records in a database by the date they were place, I want to be able to navigate through the filtered records across multiple pages. Right now, when I try to go to page 2 of the filtered records I receive the error:

String reference not set to an instance of a String. Parameter name: s `

Also, I notice that the parameters that are passed in the url change. For example:

/PurchaseOrder?searchBy=Date&dateSearchBegin=08%2F15%2F2014&dateSearchEnd=09%2F01%2F2014&dateOrderedBegin=&dateOrderedEnd=&search=

becomes when I click page 2:

/PurchaseOrder?page=2&searchBy=Date

As it currently is written in my code I am using the Request.QueryString method to try to maintain the URL but it doesn't work for dates. Is there a method that is similar to this that I can use to fix this error and achieve my desired result?

Here is my code for the controller and the view:

Controller:

else if (searchBy == "Date")
{
    if (dateSearchBegin == "" || dateSearchEnd == "")
    {
        //string message = "Both date fields are required";

    }
    else
    {
        var dtFrom = DateTime.Parse(dateSearchBegin);
        var dtTo = DateTime.Parse(dateSearchEnd);
        return View(db.PurchaseOrders.Where(x => x.Date >= dtFrom && x.Date <= dtTo).OrderBy(i => i.Date).ToPagedList(page ?? 1, 15));
    }

}
else if (searchBy == "dateOrder")
{
    if (dateOrderedBegin== ""|| dateOrderedEnd == "")
    {
        //string message = "Both date fields are required";
    }
    else
    {
        var dtFrom = DateTime.Parse(dateOrderedBegin);
        var dtTo = DateTime.Parse(dateOrderedEnd);
        return View(db.PurchaseOrders.Where(x => x.DateOrdered >= dtFrom && x.DateOrdered <= dtTo).OrderBy(i => i.Date).ToPagedList(page ?? 1, 15));
    }
}

View:

@Html.PagedListPager(
    Model, page => Url.Action("Index", 
    new { page, searchBy = Request.QueryString["searchBy"], 
    search = Request.QueryString["search"], 
    dtFrom = Request.QueryString["dtFrom"], 
    dtTo = Request.QueryString["dtTo"] }),
    new PagedListRenderOptions() { DisplayPageCountAndCurrentLocation = true,
    DisplayItemSliceAndTotal = true })

Solution

  • Your query string contains dateSearchBegin and dateSearchEnd and you are using dtFrom = Request.QueryString["dtFrom"], dtTo = Request.QueryString["dtTo"]

    Change that to same keys in Url.Action() dateSearchBegin = Request.QueryString["dateSearchBegin "], dateSearchEnd = Request.QueryString["dateSearchEnd"]

    Url.Action() will remove the null value query string args. One suggestion to check the string always use string.IsNullOrEmpty(strVar) do not use strVar == ""