Load partial page in jquery and ASP.Net MVC

In this post I will show you how much ASP.Net MVC and JQuery are making up a dangerous duet and how you can do big tasks in simple way with little efforts. We can take a look at a live example of what we will do in this post. In stackoverflow website specially users page and tags page you will find a text box to search users/tags. the page is loaded with some users info sorted with default setting. if you start to write something in that text box, the users collection will be filtered by the name you entered in ajax manner and ordered alphabetically(ascending).

The issue here is how using the same piece of code that produce the whole page when it be loaded in first time to filter the users when you type some letters in the text box and update just the part that display the users data. Here the magic of ASP.Net MVC and JQuery come to the scene.

Lets start to build our page first then start to filter our users collection. I will not show you how to create new ASP.Net MVC project this is beyond of scope of this post. I will concentrate on the pieces of code that serve the purpose of this post.

In the HomeController class we will add Index() method that will display all users into a view but we will add an optional string parameter called name that I will use to filter users collection.
public class HomeController
{
   public ActionResult Index(String name = "")
   {
      List<user> users = GetUsers()
                           .Where(u => u.Name.ToLower().StartWith(name.ToLower()) 
                                    || String.IsNullOrEmpty(search)).ToList();
      return view(users);
   }
}
Note, in Where method we select users who their name starts with the value of name variable or select all users if name variable is empty string and return the result into strongly typed view like this
@model List<user>
.
.
.
<body>
<center>
    <div>
        Find :
        <input type="text" name="search" id="search" />
    </div>
    </center>
    <br />
    <div id="usersdiv">
        <table align="center" width="30%" cellspacing="0">
            <tr>
                <td style="border-bottom: 1px solid #000">
                    ID
                </td>
                <td style="border-bottom: 1px solid #000">
                    Name
                </td>
                <td style="border-bottom: 1px solid #000">
                    Age
                </td>
            </tr>
            @foreach (var user in Model)
            {
                <tr>
                    <td style="border-bottom: 1px solid #000">@user.ID
                    </td>
                    <td style="border-bottom: 1px solid #000">@user.Name
                    </td>
                    <td style="border-bottom: 1px solid #000">@user.Age
                    </td>
                </tr>
            }
        </table>
    </div>
</body>
Till now we just display all users into a view that contains an extra textbox for filtering users. Now we will start to add the required scripts that will actually do filter by an ajax call to the Index method, the method that has been called when page loaded. in the head tag of our view we will add the following scripts
<script src="@Url.Content("https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js")" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
         $('#search').keyup(function () {
             $('#usersdiv').load('/home?name=' + $(this).val());
         });
    });
</script>
First we load jquery library itself then we declare the script that will run after loading all DOM objects of the page. We attach keyup event to the textbox to filter the users list each time we type something into textbox. load function is a jquery function that load data from the server and place the returned HTML into the matched element(using ajax call). Notice the argument that load function accept, it the url of the current page with query string(name). We set the query string paramter to the value of the textbox, that is the reason we attached keyup event not another event, keypress event for example, to get the last value of the textbox.

If we run this code as it is, that means we will load the whole html of our view into the div element with id usersdiv. But what we need is to update just the part that displays the users list. Here the magic of jquery come, we can select certain part of returned html by appending a selector to the url parameter as follows
$('#usersdiv').load('/home?name=' + $(this).val() + ' #usersdiv');
Of course you can use any valid jquery selector
Now we can filter the users list using jquery without writting any extra piece of code in server side and without reloading the whole page.
Thanks for the awesome duet, ASP.Net MVC and JQuery.

you can download the full source code here

Comments

Popular posts from this blog

Android : How to change progress bar color at runtime programmatically?

How to fire RowCommand event of nested GridView?

ASP.Net MVC : Conditional Validation using ValidationAttribute