使用jQuery和asp.net转发器自动完成填充ID

时间:2011-03-23 15:37:32

标签: jquery asp.net ajax json asmx

我有一个asp:带有自动完成功能的文本框,数据来自web服务并返回Json数据。选择项目时,它会将值(ID)放入“隐藏”字段,并将价格放入另一个文本框中。一切正常。但是当我将大致相同的代码放入asp:repeater中时,它不会执行自动完成。

这是我的asp代码:

<script src="Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui-1.8.10.custom.min.js" type="text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>

<asp:TextBox runat="server" id="txtItem2" style="width:500px"/><br />  
<asp:TextBox runat="server" ID="txtHiddenItemID2"  />  <br />  
<asp:TextBox runat="server" ID="txtPrice2" />      

<asp:Repeater ID="rptArtLijnen" runat="server" 
    onitemcommand="rptArtLijnen_ItemCommand">
    <HeaderTemplate>
        <table border="Solid">
            <tr>....
            </tr>
    </HeaderTemplate>
    <ItemTemplate>
            <tr>
                <div class="ItemAutoComplete" id="ItemAutoCompleteDiv">
                    <td>
                            <asp:TextBox runat="server"  ID="txtItem" Text='<%#Eval("Item") %>' class="txtItemclass" />
                            <asp:TextBox ID="txtHiddenItemID" runat="server" class="txtHiddenItemclass"/>               
                    </td>
                    <td><asp:TextBox runat="server" ID="txtPrice" value='<%#Eval("Price") %>'/></td>
                </div>
            </tr>               
    </ItemTemplate>
    <FooterTemplate>
     </Table>
    </FooterTemplate>
</asp:Repeater>

这是我的jQuery代码:

$(document).ready(function () {
        //this handles the textbox out of the repeater
        $.ajax({
            type: "POST",
            url: "AutoCompleteItems.asmx/GetItemJ",
            dataType: "json",
            data: "{ 'data': '" + document.getElementById("txtItem2").value + "' }",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                $('#txtItem2').autocomplete({
                    minLength: 0,
                    source: data.d,
                    focus: function (event, ui) {
                        $('#txtItem2').val(ui.item.value);
                        return false;
                    },
                    select: function (event, ui) {
                        $('#txtItem2').val(ui.item.ItemCode + " " + ui.item.Description);
                        $('#txtHiddenItemID2').val(ui.item.ID);
                        $('#txtPrice2').val(ui.item.Price);
                        return false;
                    }
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus + errorThrown);
            }
        });

        //this handles the textbox in the repeater
        $(".ItemAutoComplete").each(function (i, element) {
            var txtItem = $(this).find('input[id*=txtItem]:first')
            var txtHiddenItemID = $(this).find('input[id*=txtHiddenItemID]:first')
            var txtPrice = $(this).find('input[id*=txtPrice]:first')

            $.ajax({
                type: "POST",
                url: "AutoCompleteItems.asmx/GetItemJ",
                //async: false,
                //cache: false,
                dataType: "json",
                data: "{ 'data': '" + txtItem.val() + "' }",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    txtItem.autocomplete({
                        minLength: 0,
                        source: data.d,
                        focus: function (event, ui) {
                            txtItem.val(ui.item.value);
                            return false;
                        },
                        select: function (event, ui) {
                            txtItem.val(ui.item.ItemCode + " " + ui.item.Description);
                            txtHiddenItemID.val(ui.item.ID);
                            txtPrice.val(ui.item.Price);
                            return false;
                        }
                    });
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(textStatus + errorThrown);
                }
            });

        });
    });

这是我的webmethod(使用文本框)和类:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<ItemJ>  GetItemJ(string data) {
   List<ItemJ> ItemJs = new List<ItemJ>();
    //if (Request.QueryString["q"] != null)
    //{
        try
        {
            DataContext d = new DataContext();
            List<string> typeList = "P R".Split(" ".ToCharArray()).ToList();
            //List<string> conditionList = "A D F".Split(" ".ToCharArray()).ToList();
            ItemJs = (from i in d.Items
                      join a in d.ItemAssortments on i.Assortment equals a.Assortment
                      where a.SecurityLevel <= 999
                      where i.SecurityLevel <= 999
                             && a.SecurityLevel <= 999
                             && i.IsSalesItem == true
                             && !typeList.Contains(i.Type.ToString())
                             && (new string[] { "A", "D", "F" }).Contains(i.Condition.ToString())
                             && (SqlMethods.Like(i.Description, "%" + data + "%") || SqlMethods.Like(i.ItemCode,  data + "%"))
                      orderby i.ItemCode
                      select new ItemJ
                      {
                          //value = i.ItemCode,// + " " + i.ItemCode + " ",
                          ItemCode = i.ItemCode,
                          Description = i.Description, //+ " " + i.ItemCode + " ",
                          ID = i.ID.ToString(),
                          Price = i.PurchasePrice.ToString()
                      }).Take(10).ToList();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
            //return null;
        }
    //}
    return ItemJs;
}


public class ItemJ //: Item
{
    //string _name;
    string _value;

    public string value
    {
        get { return _Description + " (" + _ItemCode + ")"; }
        //set { _value = value; }
    }
    string _Description;

    public string Description
    {
        get { return _Description; }
        set { _Description = value; }
    }

    string _ID;

    public string ID
    {
        get { return _ID; }
        set { _ID = value; }
    }

    string _ItemCode;
    public string ItemCode
    {
        get { return _ItemCode; }
        set { _ItemCode = value; }
    }
    string _Price;

    public string Price
    {
        get { return _Price; }
        set { _Price = value; }
    }

}

我花了好几个小时,有人能给我一些线索吗?

2 个答案:

答案 0 :(得分:0)

基本上问题是,你的文本框放在转发器控件里面,因为这个jquery无法识别控件的唯一id,所以jquery自动完成的内容

尝试AutoCompleteExtender它会给你想要的输出。

答案 1 :(得分:-1)

您可以尝试从ItemAutoComplete Div中的控件中取出ID并按类搜索。当我尝试通过Id访问转发器控件中的控件时遇到此问题,因为所有ID在页面中应该是唯一的。所以而不是

var txtItem = $(this).find('input[id*=txtItem]:first')

var txtItem = $(this).find('.txtItemClass')

HTH