Jquery, Autocomplete using json, id's vs displ

2020-07-23 04:02发布

问题:

I have kind of a complicated autocomplete issue. This is for a messaging system for a website I'm working on. I want it to work where you type in a user's name, it comes back with a thumb of their image and their name and their id. Then, when you select it, I want it to show the users name, but when it posts back I want it to send back their ID (as a user's name is not unique).

I started with http://blog.schuager.com/2008/09/jquery-autocomplete-json-apsnet-mvc.html as an approach. However, I am using the tageditor.js from Stackoverflow as my extender, just because I like how it works.

the tag editor is linked below. I think it's an older version.

We are using MVC 1.0. Here's my code:

public ActionResult Recipients(string prefix, int limit)
        {
            IList<UserProfile> profiles = profileRepository.GetUsers(prefix, limit);

            var result = from p in profiles
                         select new
                         {
                             p.ProfileId,
                             p.FullName,
                             ImageUrl = GetImageUrl(p)
                         };

            return Json(result);
        }

Here's the script on the page

<script type="text/javascript">
$(document).ready( function() {  
    $('#recipients').autocomplete('<%=Url.Action("Recipients", "Filter") %>', {      
        dataType: 'json',      
        parse: function(data) {
            var rows = new Array();          
            for(var i=0; i < data.length; i++) {
                rows[i] = { data: data[i], value: data[i].ProfileId, result: data[i].FullName };
            }          
            return rows;      
        },      
        formatItem: function(row, i, n) {
            return '<table><tr><td valign="top"><img src="' + row.ImageUrl + '" /></td><td valign="top">' + row.FullName + '</td></tr></table>';
        },      
        max: 20,
        highlightItem: true,
        multiple: true,
        multipleSeparator: ";",
        matchContains: true,
        scroll: true,
        scrollHeight: 300
     });
});
</script>

So, what happens is the call back works, my list shows the image and user name, and when I select one, it puts the user's full name in the text box with the delimter. However, when I submit the form, only the names are sent back and not the profile ids. Any ideas on how to get the ID's back without displaying them in the text box?

EDIT: Here's the version of tageditor.js I'm using http://www.gotroleplay.com/scripts/tageditor.js

回答1:

I know it's lame, but I always either (a) post the data from the result handler (NOT the formatResult, which, as I understand it, just formats the result for putting in the textbox, or (b) stick the value in a hidden field -- again from the result handler -- for posting.

    $('#recipients').autocomplete({options})
     .result(function(event, data, formatted) {
         $("#hidden_field").val( data.ProfileId );
// or just post the data from in here...
    });

or something. Please let us know if you find a better way...

Obviously, posting directly from the autocomplete 'result' is only appropriate in very specific scenarios



回答2:

I think you need a formatResult. That is what I use for what is sent back to the server. I think it would look something like:

formatResult(row, i, n) {
    return row.value;
}

if the "value: data[i].ProfileId" is what you want to send.



回答3:

This answer comes nearly a year late but I've tested it and works great.

After trying lots of ways and visiting this question at SO I've finally found the best solution to display values but send IDs.

Step by Step Instructions

1- Get the "latest" version of Jörn's autocomplete jQuery plugin from the GitHub repository (the official version got merged into jQuery UI but some developers are still maintaining and updating the "standalone" one) here: jQuery AutoComplete Plugin (GitHub repository)

2- Use a JS array like this one (you can also use the AJAX way):

var categories = [
 { name: "Lawyer", id: "1" },
 { name: "Driver", id: "2" },
 { name: "Dentist", id: "3" },
];

3- Use this JavaScript function to init the plugin:

$("#category").autocomplete(categories, {
    formatItem: function(row, i, max) { return row.name; },
    formatMatch: function(row, i, max) { return row.name; },
    formatResult: function(row) { return row.name; }
});
$("#category").result(function(event, data, formatted) {
    $("#category_id").val(data["id"]);
});

4- Add another hidden field in your form like:

<input type="text" id="category" />
<input type="hidden" id="category_id" name="category_id" value="" />

PS: You may be able to use jQuery UI's Autocomplete widget since it is based in Jörn's one, haven't tested it though.