MVC 4.0: Normal vs. Ajax Search

I’m reading now Wrox Professional ASP.NET MVC 4.0, this book is really useful that I recommend to read if you want to learn MVC 4.0 and be professional.

Suppose that we have a Home Controller, in the Index View there will be a text box to enter text to search for and a button to view the search result.

We can do that by two ways:

  1. Normal Search
  2. Ajax Search

1. Normal Search

In the Index view we will Create a Form with Text box and a Search button.

@using (Html.BeginForm("Search", "Home", FormMethod.Get))
{

    <h3>Search Music Albums:</h3>
    <input type="text" name="q" />
    <input type="submit" value="Search" />
}

We can use the Html helper method to create the form, When you press the Search button the model binder will pass the text you entered as q parameter to the Search action method located in the Home controller.

        private MusicStoreDBContext storeDb = new MusicStoreDBContext();

        public ActionResult Search(string q)
        {
            var albums = storeDb.Albums.Include("Artist").Where(a => a.Title.Contains(q)).Take(10);
            return this.View(albums);
        }

The Search action method will search our Music Store and get all albums with Title contains the search text and display the result in a new view called Search.

@model IEnumerable<MvcMusicStore.Models.Album>

@{
    ViewBag.Title = "Search";
}

<h2>Search Result</h2>

<table>
    <tr>

        <th>
           Artist
        </th>
        <th>
            Title
        </th>
        <th>
            Price
        </th>

        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>

        <td>
           @item.Artist.Name
        </td>
        <td>
            @item.Title
        </td>
        <td>
            @string.Format("{0:c}", item.Price)
        </td>

    </tr>
}

</table>

In the previous scenario you enter the search text in one view and the result appears in another one.
What if we want to display the search result in the same view??

2. Ajax Search

 

In the Index view we will use the Ajax helper to create Ajax Form.

@using (Ajax.BeginForm("AjaxSearch", "Home",
    new AjaxOptions { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "searchResults" }))
{
    <h3>Search Music Albums:</h3>
    <input type="text" name="q" />
    <input type="submit" value="Ajax Search" />
}

<table id="searchResults">

</table>

Note the AjaxOptions parameter with InsertionMode and UpdateTargetId fields.

Lets have a look at AjaxSearch action method.

        private MusicStoreDBContext storeDb = new MusicStoreDBContext();

        public PartialViewResult AjaxSearch(string q)
        {
            var albums = storeDb.Albums.Include("Artist").Where(a => a.Title.Contains(q)).Take(10);
            return this.PartialView(albums);
        }

The Ajax Search uses PartialViewResult to build the search result and place it in the Index view.
The Ajax Search Partial View will only contains a table for listing the search result.

@model IEnumerable<MvcMusicStore.Models.Album>

<table>
    <tr>

        <th>
           Artist
        </th>
        <th>
            Title
        </th>
        <th>
            Price
        </th>

        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>

        <td>
           @item.Artist.Name
        </td>
        <td>
            @item.Title
        </td>
        <td>
            @string.Format("{0:c}", item.Price)
        </td>

    </tr>
}

</table>

Don’t forget to add reference to JQuery Unobtrusive Ajax script file in the _Layout.cshtml.


<script src="~/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>

When you run your application you should have something like that:

search

Thank you and Keep It Simple and Straightforward 🙂
~:H}{H:~

Advertisements

4 thoughts on “MVC 4.0: Normal vs. Ajax Search

  1. […] talked before about Ajax search but it was using Helper Methods, here we will see how to implement Ajax Search using JSON and […]

  2. This is great however, I’m finding with my query if I leave the search field blank and press search, it returns all the fields in the table which I don’t want.

    Any ideas on ideas on that?

    Cheers

  3. Nice article …. Thanks…

    If someone does not work ajax then check this two js file and also check the same sequence.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s