Wednesday, 21 May 2014

MVC JQuery AutoComplete plugin in action

In my MVC project I used JQuery auto complete plugin which had id and value. Now I'm going to show you how I had done all this.

In controller I have a method implemented like this:

public JsonResult AutocompleteSuggestions(string term)
        {
            var suggestions = unitOfWork.EmployeesRepository.Get().
                             Where(w => w.IdentificationNumber.Contains(term)).
                              Select(s => new {  value = s.EmpID, label = s.IdentificationNumber }).ToList();

               return Json(suggestions, JsonRequestBehavior.AllowGet);
        }

From View I have a textbox which I'm using for auto-complete: HTML part like this:

<input id="SearchTerm" name="searchTerm" type="text" />
<input type="hidden" id="SelectedEmpID" name="SelectedEmpID"/>

binding the textbox (id: SearchTerm) binding with JQuery like this:

<script type="text/javascript">
        $(function () {
            $("#SearchTerm").autocomplete({
                source: "/AREA_NAME/CONTROLLER_NAME/mETHOD_NAME",  
                minLength: 1,
                select: function (event, ui) {
                    $('input[name="searchTerm"]').val(ui.item.label);  // SETTING LABEL
                    $('input[name="SelectedEmpID"]').val(ui.item.value); // SETTING ID IN CURRESPONDING HIDDEN FIELD
                    return false;
                }
            });
        });

You are done!! whenever you type something in textbox it will fetch data from specified URL with that search term.
When you select item label will set in the textbox and value will be set  in the hidden field.


so, you can use the ID from that hidden field!!!

if you have any problem let me know by mail.


No comments:

Post a Comment