ASP.NET MVC > Ajax

Search database using Ajax in ASP.NET MVC

How to search records from the database using Ajax in ASP.NET MVC?


To search records from the database using Ajax, we can follow below approach.

CONTROLLER CODE

    public ActionResult Index()
      {
            return View();
      }

      public PartialViewResult SearchPeople(string keyword)
      {
          System.Threading.Thread.Sleep(2000);
          var data = db.PersonalDetails.Where(f =>
          f.FirstName.StartsWith(keyword)).ToList();
          return PartialView(data);
      }

The first controller action method simply returns the View displayed below. The 2nd method first make the thread sleep (wait) for 2000 milliseconds (2 seconds) – just to get a real time application client server request feeling. In real time scenario, we must remove this line of code (System.Threading.Thread.Sleep(2000);). This line of code is just to delay the processing so that “Loading …” message appears.

After that we search records from the database based on the keyword passed to this method. Remember that this method return type is PartialViewResult so it returns PartialView named “SearchPeople”. Look at the code is below.

PARTIAL VIEW CODE (SearchPeople partial view)

@model IEnumerable<MVCTraining5.Models.PersonalDetail>

@foreach (var p in Model)
{
    <tr>
        <td>@p.AutoId</td>
        <td>@p.FirstName</td>
        <td>@p.LastName</td>
        <td>@p.Age</td>
        <td>@p.Active</td>
    </tr>
}

In the above view, search result from the Action method is taken as model then we iterate through each item in the model and write a row with columns.

VIEW CODE (Index action method)

@model string
@{
          ViewBag.Title = "Index";
          AjaxOptions options = new AjaxOptions
          {
                 UpdateTargetId = "searchResult",
                 Confirm = "Are you sure to start search?",
                 InsertionMode = InsertionMode.Replace,
                 LoadingElementId = "divLoading"
         };
}
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
    <h2>Index</h2>
    <table style="width: 100%;">
        <thead>
            <tr>
                <th>AutoId</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Age</th>
                <th>Active</th>
            </tr>
        </thead>
        <tbody id="searchResult">
            @Html.Action("SearchPeople", new { keyword = "" })
        </tbody>
    </table>
    @using (Ajax.BeginForm("SearchPeople", options))
  {
    <div id="divLoading" style="color: red; width: 200px; background-color: yellow; fontsize: larger; display: none; position: absolute;">
        Loading ....
    </div>
    <div>
        @Html.TextBox("keyword")
        <button type="submit">Search</button>
    </div>
    }

In the above view, we are creating AjaxOptions object first and set its properties.

  • UpdateTargetId – is the element id in which the Ajax response will be updated.
  • Confirm – message to ask before submitting Ajax request
  • InsertionMode – used to instruct Ajax, whether to replace the ajax response or insert after or before. Try differet InsertionMode enumerations
  • LoadingElementId – the id the of html element that will be shown in between ajax request begins and ajax response completes.
We are referenging jquery.unobtrusive-ajax.min.js file that is used in @Ajax helper method.

Writes the header of the records to be shown. In the <tbody> the SearchPeople action method is called that returns PartialView SearchPeople.

Now when the page loads for the first time, the whole page looks like below where there is no role of Ajax.

The heading comes from the View and record comes from the SearchPeople partial view.

The next set of codes are @Ajax.BeginForm that sends the request to “SearchPeople” action method (the same that was requested in the <tbody> element) and AjaxOptions is passed that was created at the top.

Inside the form, we have a divLoading element that simply has a “Loading …” text that is hidden initially and it will be shown only when Ajax request starts and hides again when the Ajax request is complete. Then we have a textbox “keyword” and a Search button of Submit type.

When Search button is clicked, a ajax request goes to the SearchPeople action method that returns PartialView (SearchPeople with popupdated data from the search result) that is replaced with the content of “searchResult”
<tbody> element.

 Views: 43369 | Post Order: 112



Write for us






Hosting Recommendations