Loading search result without page refresh in ASP.NET MVC (Ajax)

Sheonarayan
Posted by in ASP.NET MVC category on for Intermediate level | Points: 250 | Views : 54025 red flag
Rating: 5 out of 5  
 1 vote(s)

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.


 Download source code for Loading search result without page refresh in ASP.NET MVC (Ajax)

Recommendation
Read Working with Roles in ASP.NET Identity for MVC before this article.

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.
  1. UpdateTargetId -element id within which the search result will be placed
  2. Confirm - message to show before submitting the form
  3. InsertionMode - behavior of the data to be inserted inside the UpdateTargetId (in this case, it will replace the current data)
  4. 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.

Page copy protected against web site content infringement by Copyscape

About the Author

Sheonarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: Jayakumars on: 7/4/2014 | Points: 25
Hi
Sheo
Good One but how to place partial view in my master page.I asked how to place content placeholder this partial view
finally my output shows separate page but i need my result show in my master page and shows content place
Posted by: Sheonarayan on: 7/4/2014 | Points: 25
Hi Jayakumars,

There is no concept called master page and PlaceHolder in ASP.NET MVC. You have _layout that works as Master page and then you have View. So in perspective of ASP.NET Web Form

_layout = master page
view page = content page
partial view page = user control

So you can call partial view either into _layout or view page. In this article below code snippet call my SearchPeople partial view into my view page (index.cshtml).

 @Html.Action("SearchPeople", new { keyword = "" })

Hope this will give some clue.

Thanks
Posted by: Jayakumars on: 7/4/2014 | Points: 25
hi
sheo
thanks for your reply

i need how to use master page and content page use mvc4 for CRud Operations
Posted by: Jayakumars on: 7/4/2014 | Points: 25
hi
sheo

I need how to Entry the Stundents Information and entry the Fees Entry for the

My Mvc Application how will do this any one post them.
Posted by: Ashleyalex on: 9/23/2014 | Points: 25
Am getting below error while loading the view (after executing the partial action method )

System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper
Posted by: Jayakumars on: 8/31/2015 | Points: 25
Hi
Sheo

I download this but Javascript only have. Normally we create one javascript file that js already we get so your source code not there in this attachment

I tried your piece of code not working for me not working for me. Can you share zip format source code thats helpful to others.

Login to post response

Comment using Facebook(Author doesn't get notification)