Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c# - jQuery AutoComplete multiple Output

I am using jQuery AutoComplete to fetch results from a DataBase based on the value inputted. The user will then click a search button to tell the page to search for that specific entries details.

I want to get 2 values, the Name and Title. I only want to display the Name to the user, while the page uses the Title as a search criteria.

eg: When a person types in Vehicle, the result will display Vehicle1, Vehicle2 in a list.
When the user clicks on Vehicle1, a hidden box will be issues with the Title, which would be Bike, and such as with Vehicle2, which will issue the hidden box with Car.

I can get the Name to show in the text box properly, but I cannot for the life of me (And after 2 days of searching) bind the Title to a hidden box.

JavaScript:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $(".tb").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "AutoComplete.asmx/FetchEmailList",
                        data: "{ 'prefix': '" + request.term + "' }",
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        dataFilter: function (data) { return data; },
                        success: function (data) {
                            response($.map(data.d, function (item) {
                                return {
                                    //value: item.Title,
                                    label: item.Name
                                };
                            }));
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(textStatus);
                        }
                    });
                },
                minLength: 2
            });
        });
    </script>

ASPX Code:

<div class="ui-widget" >
    <asp:TextBox ID="tbAuto" class="tb" runat="server">
    </asp:TextBox>
    <asp:TextBox runat="server" ID="tbHidden" class="tb"></asp:TextBox>
</div>

CodeBehind:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class AutoComplete : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Employee> FetchEmailList(string prefix)
{
    var emp = new Employee();
    var fetchEmail = emp.GetEmployeeList(prefix)
    .Where(m => m.Name.ToLower().StartsWith(prefix.ToLower()));
    return fetchEmail.ToList();
}    
}

CompletionClass: (Excuse the naming)

public class Employee
{
    public string Title { get; set; }
    public string Name { get; set; }
    public string value { get; set; }

    public List<Employee> GetEmployeeList(string prefixText)
    {
        List<Employee> cmpList = new List<Employee>();

        SqlConnection db = DataConn.SqlConnection();

        db.Open();
        SqlTransaction transaction = db.BeginTransaction();

        //var array = new ArrayList();

        try
        {
            SqlCommand command = new SqlCommand("Select [something] FROM vwGetDetails WHERE [something_else] LIKE N'%" + prefixText + "%' ORDER BY [thatOther_thing] ASC", db, transaction);
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    cmpList.Add(new Employee() { Name = reader["Value1"].ToString(), Title = "Value1_Cat", value = "Value1_Cat"});
                }
            }

            command = new SqlCommand("Select [something] FROM [somewhere] WHERE [thingy] LIKE N'%" + prefixText + "%' ORDER BY [previousThingy] ASC", db, transaction);
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    cmpList.Add(new Employee() { Name = reader["Value2"].ToString(), Title = "Value2_Cat", value = "Value2_Cat"});
                }
            }

            transaction.Commit();
        }
        catch (SqlException)
        {
            transaction.Rollback();
            cmpList.Add(new Employee() { Name = "Problem Getting Results.", value = "Error"});
            //array.Add("Problem Getting Results.");
        }

        if (cmpList.Count == 0)
            cmpList.Add(new Employee() { Name = "Nothing to Display.", value = "Info"});
        //array.Add("Nothing to Display.");

        //return array;

        return cmpList;
    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Those modifications to your JavaScript should do the trick:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $('input[name$="tbAuto"]').autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "AutoComplete.asmx/FetchEmailList",
                    data: "{ 'prefix': '" + request.term + "' }",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataFilter: function (data) { return data; },
                    success: function (data) {
                        response(data.d);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(textStatus);
                    }
                });
            },
            minLength: 2,
            focus: function(event, ui) {
                $('input[name$="tbAuto"]').val(ui.item.Name);
                return false;
            },
            select: function(event, ui) {
                $('input[name$="tbAuto"]').val(ui.item.Name);
                $('input[name$="tbHidden"]').val(ui.item.Title);
                return false;
            }
        }).data('autocomplete')._renderItem = function(ul, item) {
            return $('<li>').data('item.autocomplete', item).append('<a>' + item.Name + '</a>').appendTo(ul);
        };
    });
</script>

The assumption here is that the selectors returns exactly the element which we are working on, if not they need to be adjusted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...