Facebook like search Textbox in MVC 3 Razor




  1. In this article we will see how to create a autocomplete search textbox using ajax, json, jQuery and HTML in MVC3 Razor.
  2. This search textbox is similar to the one used in Facebook.
  3. We are showing the image and text.
  4. In this example, images are stored in the physical folder. We can also store images in database in form of bytes and retrieve these images from database while rendering.
  5. We have used onkeyUp event to capture the text entered by user. The text is searched in the hardcoded array of string. The result returned using json is rendered with images. 
  6. We have shown this example using MVC3 Razor application.


Following are the steps :

View :

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

<style>
    #targetUL
    {
     width: 400px;
        border: 1px solid silver;
        margin-top: 2px;
        list-style: none;
        max-height:500px;
        overflow:auto;
    }
    #targetUL li
    {
        margin-left: -40px;
        border-bottom: 1px solid silver;
        height: 60px;
        padding-left: 5px;
        padding-top : 8px;
        cursor:pointer;
    }
    #target
    {
        width:300px;
    }
    .imageClass
    {
        height:54px;
        width:40px;
    }
    .text
    {
        padding-left: 20px;
        font-family: comic sans ms;
        font-size: 20px;
        font-weight: bolder;
    }
 </style>

<div id="targetDiv">
<input type="text" id="target" />
</div>


<script type="text/javascript">
    $(document).ready(function () {

        //We have used keyup event to track the user enter value in the textbox.
        $("#target").keyup(function () {
            //Fetching the textbox value.
            var query = $(this).val();
            //Calling GetItems method.
            getItems(query);
        });

        function getItems(query) {

            //Here we are using ajax get method to fetch data from the list based on the user entered value in the textbox.
            //We are sending query i.e textbox as data.
            $.ajax({
                url: '@Url.Action( "RemoteData", "AutoComplete")',
                data: { "query": query },
                type: 'POST',
                dataType: 'json',
                success: function (response) {
                    if (response.Data != null) {
                        if ($("#targetUL") != undefined) {
                            //If the UL element is not null or undefined we are clearing it, so that the result is appended in new UL every next time.
                            $("#targetUL").remove();
                        }
                        //assigning json response data to local variable. It is basically list of values.
                        data = response.Data;
                        //appending an UL element to show the values.
                        $("#targetDiv").append($("<ul id='targetUL'></ul>"));
                        //Removing previously added li elements to the list.
                        $("#targetUL").find("li").remove();
                        //We are iterating over the list returned by the json and for each element we are creating a li element and appending the li element to ul element.
                        $.each(data, function (i, value) {
                            //On click of li element we are calling a method.
                            $("#targetUL").append($("<li class='targetLI' onclick='javascript:appendTextToTextBox(this)'><span><img class='imageClass' src='../../Content/Images/" + value + ".jpg' /></span><span class='text'>" + value + "</span></li>"));

                        });
                    }
                    else {
                        //If data is null the we are removing the li and ul elements.
                        $("#targetUL").find("li").remove();
                        $("#targetUL").remove();
                    }
                },
                error: function (xhr, status, error) {
                }
            });
        }
    });

    //This method appends the text oc clicked li element to textbox.
    function appendTextToTextBox(e) {
        //Getting the text of selected li element.
        var textToappend = e.innerText;
        //setting the value attribute of textbox with selected li element.
        $("#target").val(textToappend);
        //Removing the ul element once selected element is set to textbox.
        $("#targetUL").remove();
    }
</script>

In the View, we have created a textbox. When user enters any letter inside the textbox, onKeyUp event is fired. The letters entered is posted to the controller method using ajax post. The letters are searched in the array using linq. The result is then sent back using json. The result is then iterated and appended to li element with respective images.
             We have also defined CSS classes in the view itself to give it a proper look.

Images :


We have stored images in the folder inside the application. The image is picked from folder while rendering.




Controller :

[HttpPost]
        public ActionResult RemoteData(string query)
        {
            List listData = null;
            //checking the query parameter sent from view. If it is null we will return null else we will return list based on query.
            if (!string.IsNullOrEmpty(query))
            {
                //Created an array of players. We can fetch this from database as well.
                string[] arrayData = new string[] { "Fabregas", "Messi", "Ronaldo", "Ronaldinho", "Goetze", "Cazorla", "Henry", "Luiz", "Reus", "Neur", "Podolski" };
                
                //Using Linq to query the result from an array matching letter entered in textbox.
                listData = arrayData.Where(q => q.ToLower().Contains(query.ToLower())).ToList();
            }

            //Returning the matched list as json data.
            return Json(new { Data = listData });
        }

The above is the controller method to which user's input is posted using ajax post. The posted letters are searched in the array. We can also search database for results. The searched results are then returned as json result.

Snapshots :


1.





2.



Thus we have created a autocomplete search textbox which looks and works like facebook. We can customize it more and make it the way we require.
                 In this article we have picked images from folder and searched results in hardcoded array. We can pick images from database and can also use database to query our result.

0 comments:

Post a Comment