Saturday, January 26, 2019

Jquery UI search (autocomplete) MVC

For creating a search bar like google we can use the jquery UI plugin.

<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<label>Search fruits:</label>
<input type="text" id="txtFruits" name="txtFruits" />

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<script type="text/javascript" language="javascript">
    $(document).ready(function () {
        $('#txtFruits').autocomplete({
            source: '@Url.Action("data")'
        });
    })
</script>



// <summary>
/// Inside the controller 
/// Don't change the parameter name (term) it's default by jquery ui
/// </summary>

public ActionResult data(string term)
        {
            var items = new[] { "Apple", "Pear", "Banana", "Pineapple", "Peach" };

            var filteredItems = items.Where(item => item.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) >= 0 );

            return Json(filteredItems, JsonRequestBehavior.AllowGet);
        }

No comments:

Post a Comment

Git Commands

Git Version   To check the git version Git -v       Git Clone To clone the repository, use the following command: Git clone [u...