带有自定义格式的C#Web服务json数据jquery ui

C# Webservice json data jquery ui with custom formatting

本文关键字:json 数据 jquery ui 服务 C#Web 自定义 格式      更新时间:2023-09-26

我正在使用asp.net Web服务在jQuery UI自动完成插件中使用它,这是我得到的数据。

{"d":[
    {
        "__type":"WebS.Model.SearchModel",
        "MainCommodityId":1,
        "MainCommodityName":"Pulses",
        "SubcommodityId":3,
        "SubCommodityName":"Urid Dal",
        "BrandId":3,
        "BrandName":"President"
    },
    {
        "__type":"WebS.Model.SearchModel",
        "MainCommodityId":1,
        "MainCommodityName":"Pulses",
        "SubcommodityId":1,
        "SubCommodityName":"Red Gram",
        "BrandId":4,
        "BrandName":"President"
    }
    ]
}

这是我正在使用的脚本:

$(document).ready(function () {
    $(".input-search").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: '/WebServices/GetAllBrandNames.asmx/getAllBrands',
                data: "{ 'data': '" + request.term + "'}",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    response($.map(data.d, function (item) {
                        return {
                            value: item.BrandName,
                            label: item.SubCommodityName
                        }
                    }))
                },
                error: function (response) {
                    alert('error');
                },
                failure: function (response) {
                    alert('faii');
                }
            });
        },
        select: function (e, i) {
            console.log(i.MainCommodityId);
            console.log(i.SubcommodityId);
            console.log(i.BrandId);
        },
        minLength: 1
    }).autocomplete("instance")._renderItem = function (ul, item) {
        return $("<li></li>")
            .data("item.autocomplete", item)
            .append("<a>" + "" + item.BrandName + " in " + item.MainCommodityName + " - " + item.SubCommodityName + "</a>")
            .appendTo(ul);
    };
});

问题是:

  1. 当我尝试输入关键字say:pre时,前面提到的输出是json。然而,该列表只返回一个"主席"项目,其中应显示2个项目
  2. 添加.autocomplete("instance")._renderItem函数后,列表显示的不是值,而是"undefined-undefined"
  3. console.log在选择项目后也未定义

如何解决这些问题?

select事件的默认行为是用ui.item.value更新输入。此代码在事件处理程序之后运行。

只需使用event.preventDefault()return false阻止selectfocus上的默认操作,并使用_renderItem进行自定义下拉。

focus: function(event, ui) {
   // prevent autocomplete from updating the textbox
   event.preventDefault(); // or return false;
}
select: function(event, ui) {
   // prevent autocomplete from updating the textbox
   event.preventDefault(); 
   //do something
}

参考文献:

  1. jQuery UI自动完成示例
  2. 示例2

最后,我实现了我想要的。回答我的问题,因为这可能对某人有帮助。

javascript:

$(document).ready(function () {
    $(".input-search").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: '/WebServices/GetAllBrandNames.asmx/getAllBrands',
                data: "{ 'data': '" + request.term + "'}",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    response($.map(data.d, function (item) {
              // don't forget to $.map to (data.d where d is the top node
                        return {
             // assign values from json response for further use
                            brandid: item.BrandId,
                            brand: item.BrandName,
                            maincommodityid: item.MainCommodityId,
                            maincommodity: item.MainCommodityName,
                            subcommodityid: item.SubcommodityId,
                            subcommodity: item.SubCommodityName
                        }
                    }));
                },
                error: function (response) {
                    alert('Server Error. Please try again.');
                },
                failure: function (response) {
                    alert('Failed to get result');
                }
            });
        },
        focus: function (event, ui) {
            // prevent autocomplete from updating the textbox
            event.preventDefault();
        },
        select: function (event, ui) {
            // prevent autocomplete from updating the textbox
            event.preventDefault();
            // do further action here such as assigning id to hidden field etc. 
            $(".input-search").val(ui.item.brand);
            // navigate to the selected item's url ex: /catalogue/1/1/pulses/red-gram/4/president
            var str = "/catalogue/" + ui.item.maincommodityid + "/" +
                 ui.item.subcommodityid + "/" + $.trim(ui.item.maincommodity.replace(/'s+/g, '-').toLowerCase()) + "/" +
                 $.trim(ui.item.subcommodity.replace(/'s+/g, '-').toLowerCase()) + "/" + ui.item.brandid + "/" +
                  $.trim(ui.item.brand.replace(/'s+/g, '-').toLowerCase());
            window.location = str;
        },
        minLength: 3
    }).autocomplete("instance")._renderItem = function (ul, item) {
        // get values and create custom display
        var $a = $("<a></a>");                  
        $("<strong></strong>").text(item.brand).appendTo($a);
        $("<span></span>").text(" in ").appendTo($a);
        $("<span></span>").text(item.subcommodity).appendTo($a);
        return $("<li></li>").append($a).appendTo(ul);
    };
});

CSS:

    ul.ui-front {
        z-index: 1200; // change z-index according to your UI.
    }

通常我都是这样做的。

$(document).ready(function () {
var jsondata=array();
$.post("/WebServices/GetAllBrandNames.asmx/getAllBrands",{data: request.term},function(data){
var data=JSON.parse(data);
$.each(data.d, function( index, value ) {
  jsondata[index].value=value;
 });
$(".input-search").autocomplete({
    source:jsondata,
    //other property and events
 })
});

我的意思是在完成请求后应用源JSON,因为有时若AJAX需要一些时间来加载执行指针,仍然可以在不等待响应的情况下执行其余代码。

我没有测试这个代码,但我总是这样做,从来没有得到你的错误。好运