0

I got some great help in this thread. But one problem remains, and Im struggling with it for a few hours now. For my autocomplete feature I want to use entries that are generated from my controller and not generate an array every time. I know how to normally include my controller as source for the autocomplete feature, thats no problem for me. But how would I include my controller path e.g. "/AutoCompleteFeatures/AutoCompleteSentenceSuggestion" in this fiddle? Everything should be the same, just that the source is no array but my controller path to deliever the values I need.

JS Fiddle

$(function () {
    var availableTags = [
        "ActionScript",
        "AppleScript",
    ],
      mL = 3;

    function split(val) {
        return val.split("\n");
    }

    function extractLast(term) {
        return split(term).pop();
    }

    $("#SentenceSuggestionField1")
    .autocomplete({
          minLength: mL,
          source: function (request, response) {
              // delegate back to autocomplete, but extract the last term
              var lastTerm = extractLast(request.term);
              if (lastTerm.length >= mL) {
                  response($.ui.autocomplete.filter(availableTags, lastTerm));
              }
          },
          select: function (event, ui) {
              var terms = split(this.value);
              // remove the current input
              terms.pop();
              // add the selected item
              terms.push("\u2022 " + ui.item.value);
              // Format value to display
              terms.push("");
              this.value = terms.join("\r\n");
              return false;
          }
      });
});
`

Im struggling with this for a few hours now and tried many different things. But none of that worked yet, for example I tried to create an JS Array with values from database and use it like it in the fiddle, but that didnt work out. I tried several examples with my controller path as source, but that didnt work out too... So I hope you have a tip or hint for me, how to do this. Thank you!

As requested the controller action:

public JsonResult AutoCompleteField1(string term)
{
    var data = db.SentenceSuggestions
        .Where(s => s.SuggestionText.ToLower()
        .Contains(term.ToLower()))
        .Select(x => new { label = x.SuggestionText })
        .ToArray();
    return Json(data, JsonRequestBehavior.AllowGet);
}
Community
  • 1
  • 1
RawMVC
  • 123
  • 1
  • 15
  • Show your controller method that returns the data you want (your `source` function needs to make an ajax call) –  Feb 26 '17 at 22:40
  • @StephenMuecke I added my controller action as an Update in my post. – RawMVC Feb 26 '17 at 22:47
  • 1
    Refer [this answer](http://stackoverflow.com/questions/39217750/mvc-autocomplete-editorfor-while-using-html-begincollectionitem/39284188#39284188) for an example of what the code for the `source` function should look like. But there is a lot of other stuff in you code which is really not making sense, in particular what your trying to do in the `select` function. And the plugin has a option `minLength: 3` which you set if you want to enter 3 characters before making the call to the server –  Feb 26 '17 at 22:54
  • 1
    Have just seen a couple of your previous questions and it appears you attaching this to a ` –  Feb 26 '17 at 23:27
  • @StephenMuecke I cannot say how thankful Iam that guys like you are around here, to help beginners like me. I read your answer with the link to the other thread, created my ajax call, and it works like it should. So thanks for your help here, but most importantly, for all the help you provided to me till now. I just read your last comment, I will give that a try, it sounds like a better solution like the current workaround with mL. – RawMVC Feb 26 '17 at 23:31

2 Answers2

0

This is the working code, including the ajax call:

$("#SentenceSuggestionField1")
    .autocomplete({
          minLength: mL,
          source: function (request, response) {
              $.ajax({
                  type: "GET",
                  url: "/AutoComplete/AutoCompleteField1/",
                  data: { term: extractLast(request.term) },
                  contentType: "application/json",
                  dataType: "json",
                  success: function (result) {
                      var lastTerm = extractLast(request.term);
                      if (lastTerm.length >= mL) {
                          response($.ui.autocomplete.filter(result, lastTerm));
                      }
                  }
              })
          },
          select: function (event, ui) {
              var terms = split(this.value);
              // remove the current input
              terms.pop();
              // add the selected item
              terms.push("\u2022 " + ui.item.value);
              // Format value to display
              terms.push("");
              this.value = terms.join("\r\n");
              return false;
          }
      });
RawMVC
  • 123
  • 1
  • 15
0

Keep it simple.

This is working example from one of my projects:

Server side:

    public ActionResult autocomplete(string term)
    {
        var terms = _termRepository.search(term);
        var result = new List<AutocompleteTerm>();

        foreach (var item in terms)
        {
            result.Add(new AutocompleteTerm { id = item.id, label = item.term_name, value = item.term_name, description = item.term_description , termclass = (int)item.term_class});
        }
        return Json(result, JsonRequestBehavior.AllowGet);
    }

Term class:

public class AutocompleteTerm
{
    public int id;
    public string description;
    public string label;
    public string value;
    public int termclass;
}

jQuery:

var url = '/terms/autocomplete';

$('#search').autocomplete({
                source: url,
                minLength: 2,
                width: 800,
                select: function (event, ui) {
                    $('#result').html(ui.item.description);
                    $('#result-class').html(ui.item.termclass);
                    $('.results').show();
                }
            });

HTML

<input type="search" placeholder="search" class="form-control" id="search">

<div class="top-buffer display-none results">
<blockquote id="result"></blockquote>
<blockquote>Class: <span id="result-class"></span></blockquote>
</div>
Artur Kedzior
  • 3,994
  • 1
  • 36
  • 58