ASP.NET MVC > Entity Framework

Search based on keyword in ASP.NET MVC

How to perform a search based on a keyword from the database table in ASP.NET MVC?


To demonstrate this we are extending previous example in which we would be implementing search as well as sorting and paging. Below is the code of action method that accepts one more parameter called “keyword”.

CONTROLLER CODE

        /// <summary>
        /// Sort and paginate records from the database
        /// </summary>
        /// <param name="sortOn">field to sort on field</param>
        /// <param name="orderBy">order by ascending or descending</param>
        /// <param name="pSortOn">previous sorted on field</param>
        /// <param name="keyword">keyword to search from the database</param>
        /// <param name="page">page number to show</param>
        /// <returns></returns>
        public ActionResult PagingSortingAndSearching(string sortOn, string orderBy,
string pSortOn, string keyword, int? page)
        {
            int recordsPerPage = 3;
            if (!page.HasValue)
            {
                page = 1; // set initial page value
                if (string.IsNullOrWhiteSpace(orderBy) || orderBy.Equals("asc"))
                {
                    orderBy = "desc";
                }
                else
                {
                    orderBy = "asc";
                }
            }
            
            // override the sort order if the previous sort order and current
request sort order is different
            if (!string.IsNullOrWhiteSpace(sortOn) && !sortOn.Equals(pSortOn,
StringComparison.CurrentCultureIgnoreCase))
            {
                orderBy = "asc";
            }

            ViewBag.OrderBy = orderBy;
            ViewBag.SortOn = sortOn;
            ViewBag.Keyword = keyword;

            var list = db.PersonalDetails.AsQueryable();

            switch (sortOn)
            {
                case "FirstName":
                    if (orderBy.Equals("desc"))
                    {
                        list = list.OrderByDescending(p => p.FirstName);
                    }
                    else
                    {
                        list = list.OrderBy(p => p.FirstName);
                    }
                    break;
                case "LastName":
                    if (orderBy.Equals("desc"))
                    {
                        list = list.OrderByDescending(p => p.LastName);
                    }
                    else
                    {
                        list = list.OrderBy(p => p.LastName);
                    }
                    break;
                case "Age":
                    if (orderBy.Equals("desc"))
                    {
                        list = list.OrderByDescending(p => p.Age);
                    }
                    else
                    {
                        list = list.OrderBy(p => p.Age);
                    }
                    break;
                default:
                    list = list.OrderBy(p => p.AutoId);
                    break;
            }
            if (!string.IsNullOrWhiteSpace(keyword))
            {
                list = list.Where(f => f.FirstName.StartsWith(keyword));
            }
            var finalList = list.ToPagedList(page.Value, recordsPerPage);
            return View(finalList);
        }

Notice the highlighted code above. The first is in the parameter of the action method in which we have keyword parameter that will have the keyword to search in the database. The last highlighted lines checks for the value of the keyword, if its null or empty it ignores the search filter and gives all records from the database.

If keyword has some value, it search the sorted results based where FirstName starts with keyword. Similarly, we can also try to search on different fields or more than one fields.

VIEW CODE

@using PagedList;
@using PagedList.Mvc;
@model IPagedList<WebApplication1.Models.PersonalDetail>

@{
  ViewBag.Title = "Paging Sorting And Searching";
}

<h2>Paging Sorting And Searching</h2>

    <fieldset>
        <legend>Search</legend>
        @using (Html.BeginForm())
{
        <p>
            Keyword :
            <input type="text" name="keyword" required value="@ViewBag.Keyword" />
            <input type="submit" value="Search" />
            @Html.ActionLink("Create New",
"Create")
        </p>
        }
    </fieldset>
    <table class="table">
        <tr>
            <th>Auto Id
            </th>
            <th>@Html.ActionLink("First Name", "PagingSortingAndSearching", new { sortOn
= "FirstName", orderBy = ViewBag.OrderBy, pSortOn = ViewBag.SortOn, keyword =
ViewBag.Keyword })
            </th>
            <th>@Html.ActionLink("Last Name", "PagingSortingAndSearching", new { sortOn
= "LastName", orderBy = ViewBag.OrderBy, pSortOn = ViewBag.SortOn, keyword =
ViewBag.Keyword })
            </th>
            <th>@Html.ActionLink("Age", "PagingSortingAndSearching", new { sortOn =
"Age", orderBy = ViewBag.OrderBy, pSortOn = ViewBag.SortOn, keyword =
ViewBag.Keyword })
            </th>
            <th>Active</th>
            <th></th>
        </tr>

        @foreach (var item in Model) {
        <tr>
            <td>@Html.DisplayFor(modelitem => item.AutoId)
            </td>
            <td>@Html.DisplayFor(modelItem => item.FirstName)
            </td>
            <td>@Html.DisplayFor(modelItem => item.LastName)
            </td>
            <td>@Html.DisplayFor(modelItem => item.Age)
            </td>
            <td>@Html.DisplayFor(modelItem => item.Active)
            </td>
            <td>@Html.ActionLink("Edit", "Edit", new { id=item.AutoId }) |
@Html.ActionLink("Details", "Details", new { id=item.AutoId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.AutoId })
            </td>
        </tr>
        }
    </table>
    <div class="pagedList">
        @Html.PagedListPager(Model, page => Url.Action("PagingSortingAndSearching", new
{ page, sortOn = ViewBag.SortOn, orderBy = ViewBag.OrderBy, pSortOn =
    ViewBag.SortOn, keyword = ViewBag.Keyword }),
PagedListRenderOptions.ClassicPlusFirstAndLast)
    </div>

Notice the highlighted code above. We have added keyword parameter into the @Html.ActionLink as well that is the part of the header. Similarly, we have also added keyword parameter in the @Html.PagedListPage method as we need to persist the keyword both in sorting and paging.


 Views: 24118 | Post Order: 108



Write for us






Hosting Recommendations