Wednesday, February 10, 2016

Autocomplete in ASP.NET MVC

Here is my autocomplete in a project. You can use this:
1. "txtCostPNM" is an id in the textbox where autocomplete needed
2. "TagSearch" method name and "CostPoolReport" controller name
3. COSTPNM and COSTPID returned from the method and then assign these values to the textbox

You need to make your own method. Here I just request data from view and catch data from controller for assigning the value.

$('#txtCostPNM').autocomplete(
            {
                source:function(request, response) {
                 
                    //var changedText2 = $("#txtcompid").val();
                    //var changedText3 = $("#TransactionDate").val();
                    $.ajax({

                        url:'@Url.Action("TagSearch", "CostPoolReport")',
                        type: 'GET',
                        cache: false,
                        data: { term: request.term},
                        dataType: 'json',
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                                    label: item.COSTPNM,
                                    value: item.COSTPNM,
                                    id: item.COSTPID,
                               


                                };
                            }));
                        }
                    });
                },
                select:  function (event, ui) {
                    $('#txtCostPNM').val(ui.item.label);
                    $('#txtCostPID').val(ui.item.id);

               
                    //txtOneChanged();

                    //return false;
                },
                change: $('#txtCostPNM').keyup(_.debounce(txtOneChanged, 100)),
             
             

         

            });




   function txtOneChanged() {
            var changedText = $("#txtCostPNM").val();
            var txtBox = document.getElementById('txtCostPNM');
            var txtBox1 = document.getElementById('txtCostPID');
            $.getJSON(
                '/CostPoolReport/ItemNameChanged', { "ChangedText": changedText },
                function (result) {
                    txtBox.value = result.Costname;
                    txtBox1.value = result.Costpid;

                    //document.getElementById("txtCostPNM").focus();
                });
        }

No comments:

Post a Comment