使用 AJAX 和 Jquery 自动完成功能填充表单数据



我想用自动完成的选定项目填写我的表单数据。我的自动完成工作正常,但我无法弄清楚如何通过从自动完成文本框中检索项目来填写我的表单数据。这是我的代码

[HttpPost]
public JsonResult GetAutocomplete(string term)
{
    var custo = (from customer in db.tbl_Customers
                 where customer.Name.Contains(term)
                 select new { label = customer.Name, val = customer.customer_ID }).ToList();
    return Json(custo);
}
[HttpPost]
public JsonResult GetDetails(string id)
{
    tbl_Customers custodetail = db.tbl_Customers.Single(x => x.customer_ID.ToString() == id);
    return Json(custodetail, JsonRequestBehavior.AllowGet);
}

cshtml View 中的 Ajax Function

function custoautocomplete()
{
    $(function () {
        $("#Customer_ID").autocomplete({
            source: function (request, response) {
                $.ajax({
                    cache: false,
                    async: false,
                    url: '/Orders/GetAutocomplete/',
                    data: "{ 'term': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data, function (item) {
                            return item;
                        })),
                        function (item) {
                            $.ajax({
                                cache: false,
                                async: false,
                                type: "POST",
                                url: '/Orders/GetDetails/',
                                data: { "id": data.item.Customer_ID},
                            success: function (data) {
                                $('#Customer_Contact').val(data.Customer_Contact)
                                $("#Billing_Address").val(data.Billing_Address)
                                $("#Shipping_Address").val(data.Shipping_Address)
                            }
                        });
                    }
                });
            }
        });
    });
}

您需要处理 .select 事件,并让 ajax 调用那里以根据所选值更新 DOM。您还应该在 source 事件的 ajax 调用中进行更改,如下所示

$("#Customer_ID").autocomplete({
    source: function (request, response) {
        $.ajax({
            cache: false,
            // async: false, NEVER do this
            url: '@Url.Action("GetAutocomplete", "Orders")', // don't hard code your url's
            data: { term: request.term }, // change
            dataType: "json",
            type: "POST",
            // contentType: "application/json; charset=utf-8", delete
            success: function (data) {
                response($.map(data, function (item) {
                    return { 
                        label: item.label, 
                        id: item.id
                    }
                }));
            }
        })
    },select: function(event, ui) {
        $.ajax({
            cache: false,
            type: "POST",
            url: '@Url.Action("GetDetails", "Orders")',
            data: { id: ui.item.value },
            success: function (data) {
                $('#Customer_Contact').val(data.Customer_Contact)
                $("#Billing_Address").val(data.Billing_Address)
                $("#Shipping_Address").val(data.Shipping_Address)
            }
        });
    }
});

作为旁注,您不需要在GetDetails()方法中JsonRequestBehavior.AllowGet,因为它标记为[HtpPost]。此外,您应该返回一个匿名对象(当您从不使用它时,通过网络发送额外的数据是没有意义的(,例如

var custodetail = db.tbl_Customers
    .Single(x => x.customer_ID == id) // .ToString() not required - see below
    .Select(x => new
    {
        Customer_Contact = x.Customer_Contact,
        ....
    };

并且您的参数应与customer_ID的类型相同,例如

public JsonResult GetDetails(int id)

您还需要将GetAutocomplete修改为

var custo = (from customer in db.tbl_Customers
             where customer.Name.Contains(term)
             select new { label = customer.Name, id = customer.customer_ID });
return Json(custo);

我来得很晚,但我认为你不需要调用两个不同的操作。这可以在第一次调用本身中实现。我已经为我的一个项目实现了完全相同的事情。

编辑控制器代码以立即返回数据:

public JsonResult GetAutocomplete(string term)
{
    var custo = (from customer in db.tbl_Customers
                 where customer.Name.Contains(term)
                 select new { label = customer.Name, val = customer.customer_ID, contact = Customer_Contact, billingAddress = Billing_Address}).ToList();
    return Json(custo);
}

检查此 ajax 代码:

    $(function () {
                $('.autofill').autocomplete({
                    source: function (request, response) {
                        $.ajax({
                            url: "/Order/GetLocations",
                            type: "POST",
                            dataType: "JSON",
                            contentType: "application/json; charset=utf-8",
                            data: "{ 'Prefix' : '" + request.term + "', 'Search' :'" + $(this.element).attr('search') + "' }",
                            success: function (data) {
                                response($.map(data, function (item) {
                                    return {
                                        lable: item.label,
                                        value: item.val,
                                        contact: item.contact,
                                        billingAddress: item.billingAddress
                                    }
                                }))
                            },
                            error: function (response) {
                                alert(response.responseText);
                            },
                            failure: function (response) {
                                alert(response.responseText);
                            }
                        });
                    },
                    select: function (e, i) {
                        var _type = e.target; //get the control that caused the auto complete event  
  $("#Billing_Address").val(data.Billing_Address).val(i.item.billingAddress);
                    },
                    minLength: 3
                });
            })

最新更新