0

Question:
In jQuery UI Autocomplete text box ( ASP.NET MVC 5 Razor environment ), When the user selects a value, the other fields on the form should be filled automatically

Below is AutoComplete implementation. (so far it works)

<script type="text/javascript">
$(function () {
    $("#txtSearch").autocomplete({
        source: '@Url.Action("GetItemCode")',
        minLength: 1
    });
});
</script>

Now, when the user selects an item from autocomplete textbox, the other fields on the form should get filled.

Tried to implement the jQuery Autocomplete API docs, on select but to no avail

select: function (event, ui) {
         //fill selected customer details on form
         $.ajax({
             cache: false,
             async: false,
             type: "POST",
             url: "@(Url.Action("GetItemDetails", " Home"))",
            data: { "id": ui.item.Id },

            success: function (data) {
                $("#ItemName").val(data.ItemName);
               ...
               ...

getting nothing but errors:

  1. undefined, // json undefined
  2. 500 Internal Server Error // json

As Said, the autocomplete is working, I am looking for the details ( other form controls - textboxes ) to autofill on value selection from autocomplete textbox.

Irf
  • 4,285
  • 3
  • 36
  • 49
  • `$("#ItemName").val(data.ItemName);` –  Jun 25 '16 at 12:08
  • I am making a question and answer, Answer is ready .. jus few edits, and thanks .. the item/data.. was jus a typo.. basically there was the need to handle array in json data returned.. wait a while while I answer it completely – Irf Jun 25 '16 at 12:20
  • 1
    SO is not a blog site. Your question does not even indicate what the problem is. And the code in your answer does not answer a question because there is no question to answer. –  Jun 25 '16 at 12:23
  • ok I have reworded it, Does it fit SO now .. – Irf Jun 25 '16 at 12:26
  • Its still not a question! No where in it do you indicate what is not working, or what the controller method is or what data it returns or what the html is. –  Jun 25 '16 at 12:31
  • mentioned my errors and other details in much clearer fashion, if that's what's required. – Irf Jun 25 '16 at 12:42
  • No, because there is no information in the question to allow it to be answered. Refer [this question/answer](http://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system-int32-but-must-be-o) for an example - I created it primarily to dupe-hammer numerous other similar questions. There is nothing wrong with creating your own question/answer, but it needs to be a clear problem statement, not just a vehicle for you to write some code in an answer. –  Jun 25 '16 at 12:48
  • people for whom it is written will automatically reach here and get benefited. the details in the questions are enough for them. – Irf Jun 25 '16 at 13:17

2 Answers2

2

Answer:

a working implementation:

<link rel="stylesheet" href="@Url.Content("//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css")">   
<script src="@Url.Content("//code.jquery.com/jquery-1.10.2.js")"></script>
<script src="@Url.Content("//code.jquery.com/ui/1.11.4/jquery-ui.js")"></script>

<script type="text/javascript">
$(function () {
$("#ItemCode").autocomplete({
        source: function (request, response) {
            var itemnamecodes = new Array();
            $.ajax({
                async: false, cache: false,
                //type: "POST",
                url: "@(Url.Action("GetItemCode", "Home"))",
                data: { "term": request.term },
                success: function (data) {
                    for (var i = 0; i < data.length ; i++) {
                        itemnamecodes[i] = { label: data[i].Value, Id: data[i].Key };
                    }
                 }
            });
            response(itemnamecodes);
        },
         select: function (event, ui) {                 
             $.ajax({
                 cache: false, async: false, type: "POST",
                 url: "@(Url.Action("GetItemDetails", "Home"))",
                 data: { "id": ui.item.Id },                    
                success: function (data) {                       
                    var item = data[0];                          
                    $("#ItemName").val(item.ItemName);
                    $("#ItemModel").val(item.ItemModel);                       
                    ... the other details you need 
                    action = data.Action;
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert('Failed to retrieve Item.');
                }
            });
        }
});      
});
</script>

@using (Html.BeginForm())
{
 ...
  @Html.EditorFor(model => model.ItemCode, ...
  @Html.EditorFor(model => model.ItemName, ...
  ... other form elements to show details

In Controller,

  public JsonResult GetItemCode(string term)
  {        
       // var codes = db.w_Items.Where(i => i.ItemCode.StartsWith(term)).ToList();
        var result = new List<KeyValuePair<string, string>>();
        var namecodes = new List<SelectListItem>();
        namecodes = (from u in db.w_Items select new SelectListItem { Text = u.ItemCode, Value = u.w_ItemId.ToString() }).ToList();

        foreach (var item in namecodes)
        {
            result.Add(new KeyValuePair<string, string>(item.Value.ToString(), item.Text));
        }

        var namecodes1 = result.Where(s => s.Value.ToLower().Contains
                    (term.ToLower())).Select(w => w).ToList();
     return Json(namecodes1, JsonRequestBehavior.AllowGet);
  }

  [AcceptVerbs(HttpVerbs.Post)]
  public JsonResult GetItemDetails(int id)
  {            
        var codeList = db.w_Items.Where(i => i.w_ItemId == id).ToList();

        var viewmodel = codeList.Select(x => new
        {
            Id = x.w_ItemId,
            ItemName = x.ItemName,
            ItemModel = x.ItemModel,               
            ... the other details you need

        });

        return Json(viewmodel);           
   }

Two things that were irking:
(Solutions here)
the json data is in the form of array, so you need to treat it likewise:

var item = data[0];

and another very irking thing.. solution now:

you need to pass viewmodel with specific properties as json result to be handled in View

Irf
  • 4,285
  • 3
  • 36
  • 49
1

This is how I did it hope it helps.


Css


enter code here.isloading1 {   
background-color: #ffffff;
background-image: url("http://loadinggif.com/images/image-selection/3.gif");
background-size: 16px 16px;
background-position:right center;
background-repeat: no-repeat;
}

thanks to TejSoft

Controller

    [HttpPost]
    public JsonResult AutoComplete(string prefix)
    {
        var customers = _CustomerRepo.getCustomerDetails(prefix);
        return Json(customers);
    }

JS

$(function () {
$("#Customer_Name").autocomplete({
    source: function (request, response) {
        $.ajax({
            url: '/Controller/AutoComplete/',
            data: "{ 'prefix': '" + request.term + "'}",
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                response($.map(data, function (item) {


                    return {
                        //value is the default list value in auto compleate drop down
                        value: item.CustomerName,
                        id: item.CustomerID,
                        CustomerAddress: item.CustomerAddress,
                        CustomerCity: item.CustomerCity,
                        CustomerPostcode: item.CustomerPostcode

                    };

                }));
            },
            error: function (response) {
                alert(response.responseText);
            },
            failure: function (response) {
                alert(response.responseText);
            }
        });
    },

    select: function (e, i) {
        //TestCode
        // alert("CustomerName - " + i.item.value + " PostCode - " + i.item.CustomerPostcode + " CustomerCity - " + i.item.CustomerCity + " CustomerAddress - " + i.item.CustomerAddress);

        //set value for hiden field
        $("#pickup_addressline2").val(i.item.CustomerAddress);
        $("#CustomerCity").val(i.item.CustomerCity);
        $("#CustomerID").val(i.item.ID);
        $("#CustomerPostcode").val(i.item.CustomerPostcode);
    },
    minLength: 1,
    /* Show spinner while loading data #2 */
    search: function () {
        $("#Customer_Name").addClass("isloading1");
    },
    response: function () {
        $("#Customer_Name").removeClass("isloading1");
    }


});
});
Manik
  • 97
  • 1
  • 7