1

the search Filter keeps resetting when switching pages. I use Viewdata to store the string. Should I use Viewbag instead?

Controller:

        public ActionResult Index(int page = 1, int pageSize = 20, string searchString = "")
        {
            var reiseDao = new ReisenDao();
            var model = reiseDao.ListMitarbeiters(page, pageSize);

            ViewData["CurrentFilter"] = searchString;
            var persons = from p in _db.Person
                          select p;
            persons = persons.Where(s => s.Status == true);

            if (!String.IsNullOrEmpty(searchString))
            {
                persons = persons.Where(s => s.Name.Contains(searchString)
                                        || s.Vorname.Contains(searchString)
                                        || s.Kostenstelle.ToString().Contains(searchString));
            }

            return View(persons.ToPagedList(page, pageSize));

        }

The View:

                @using (Html.BeginForm())
                {
                    <p>
                        @Html.TextBox("searchString")
                        <button class="icon"><i class="fa fa-search"></i></button>
                    </p>
                }
@Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
Eden
  • 61
  • 5

2 Answers2

2

Use Sessions

The session is a State Management Technique. A Session can store the value on the Server. It can support any type of object to be stored along with our own custom objects. A session is one of the best techniques for State Management because it stores the data as client-based, in other words, the data is stored for every user separately and the data is secured also because it is on the server.

public ActionResult Index(int page = 1, int pageSize = 20, string searchString = "")
{
    var reiseDao = new ReisenDao();
    var model = reiseDao.ListMitarbeiters(page, pageSize);

    Session("CurrentFilter") = searchString;
    var persons = from p in _db.Person
                  select p;
    persons = persons.Where(s => s.Status == true);

    if (!String.IsNullOrEmpty(searchString))
    {
        persons = persons.Where(s => s.Name.Contains(searchString)
                                || s.Vorname.Contains(searchString)
                                || s.Kostenstelle.ToString().Contains(searchString));
    }

    return View(persons.ToPagedList(page, pageSize));
}

then use Session["CurrentFilter"].ToString() in entire project to get Data

For more details check this in Microsoft docs : ASP.NET Session

How to store session data in .NET MVC 5

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Abdelrahman Gamal
  • 470
  • 1
  • 5
  • 15
1

Please assign the ViewData value to the textbox.

@using (Html.BeginForm())
{
    <p>
        @Html.TextBox("searchString", ViewData["CurrentFilter"])
        <button class="icon"><i class="fa fa-search"></i></button>
    </p>
}
Nagaraj Raveendran
  • 1,150
  • 15
  • 23