In this article, we shall learn how to load search result from the database without page refresh in ASP.NET MVC. All this we are going to achieve using ASP.NET MVC Ajax helper methods.
Introduction
Avoiding page refresh is one of the best thing we can do in our website or application to make it more appealing, user friendly and fast. In this article, we are going to learn how to load search results from the database without page refresh using ASP.NET MVC Ajax helper methods.
Creating an Ajax form in ASP.NET MVC
To create an AJAX form in ASP.NET MVC, create a view called Index.cshtml and write following code
@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>
<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;font-size:larger;display:none;position:absolute;">Loading ....</div>
<div>
@Html.TextBox("keyword")
<button type="submit">Search</button>
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
IMPORTANT: It is important to keep the jquery.unobtrusive-ajax.min.js
file (after the jQuery file in the source code) in order to work with the ASP.NET MVC Ajax helper methods otherwise these methods works as HTML Helper method and posting data refreshes the page. You can download the .js file as attachment of this article.
In the above code snippet, we have following
We have created AjaxOptions
object with certain properties that will help us in controlling the behavior of Ajax form.
UpdateTargetId
-element id within which the search result will be placedConfirm
- message to show before submitting the formInsertionMode
- behavior of the data to be inserted inside the UpdateTargetId (in this case, it will replace the current data)LoadingElementId
- element to show while the form is being submitted and resultant data is loaded to the UpdateTargetId element.
Next, we have heading of the table column to be displayed as search result.
searchResult
is the element id within which we want to place the search result that will come from the partial view (SearchPeople.cshtml) that we are going to create later on.
At last we have created an Ajax form using Ajax.BeginForm helper method by passing AjaxOptions object. In this form, we have a keyword
textbox and a Search button.
SearchPeople.cshtml partial view
The SearchPeople partial view is responsible to loop through collection of search results.
@using Restaurant.Models
@model IEnumerable<PersonalDetail>
@foreach (PersonalDetail 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 code snippet, we have a
foreach
loop that is looping through PersonalDetail IEnumerable collection and framing the search result data in the form of row and column.
ASP.NET MVC Controller method
The controller method in this case returns PartialViewResult and here is the code for that.
Models.TrainingMVCContext db = new Models.TrainingMVCContext();
public PartialViewResult SearchPeople(string keyword)
{
// System.Threading.Thread.Sleep(2000);
var data = db.PersonalDetails.Where(f => f.FirstName.Contains(keyword)).ToList();
return PartialView(data);
}
In the above code snippet, we are returning PartialView with collection of records from the database using LINQ where first name contains a character(s) coming in as keyword
from the ajax form.
How this whole ASP.NET MVC Ajax Search page works
When the page loads for the first time, @Html.Action("SearchPeople", new {keyword = ""})
code executes and calls the SearchPeople partial view that in tern call SearchPeople action method of the controller. The controller action method gets all the data from the database as there is nothing passed as keyword
.
When user writes few characters in the keyword
TextBox and click Search button, he/she is given a confirmation message specified in the AjaxOptions object. If user confirms, the form gets submitted partially (not complete page post back) to the SearchPeople action method of the controller that returns SearchPeople partial view after populating search result data. This data is then populated within searchResult
element specified in the AjaxOptions. If this whole process takes more than 2 seconds (standard time set in ajax request), the divLoading
element is shown to the user on the page that shows Loading .... status message.
Source code: Feel free to download the source code from the source code link placed at the top.
Hope this article was useful, please let me know your feedback or suggestions for improvement if any.
Thanks for reading and do share this article to your social pages if this helps.