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

时间:2017-11-11 04:57:52

标签: ajax asp.net-mvc jquery-ui jquery-ui-autocomplete

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

[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视图中的Ajax函数

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)
                            }
                        });
                    }
                });
            }
        });
    });
}

2 个答案:

答案 0 :(得分:0)

您需要处理.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)
            }
        });
    }
});

作为旁注,自标记为JsonRequestBehavior.AllowGet以来,GetDetails()方法中不需要[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);

答案 1 :(得分:0)

我对此很迟,但是我认为您不需要调用两个不同的动作。这可以在第一个电话本身中实现。我已经为我的一个项目实施了完全相同的事情。

编辑您的控制器代码以一次返回数据:

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
                });
            })