Search code examples
asp.net-mvc-3jquery-tokeninput

How to fire controller with JQuery and tokenInput


I am using TokenInput and MVC 3 C#.

I would like to get this bit of JQuery to work, but it never passes in the string to the method in my controller class from the input box. What am I doing wrong.

Create.cshtml

<input type="text" id="authorlist" name="q" data-autocomplete="@Url.Action("GetAuthors", "Author")" />

AuthorController.cs

public ActionResult GetAuthors(string term)
        {
            term = term.ToUpper();
            var authors = db.AUTHOR
                .Where(a => a.FULL_NAME.ToUpper().StartsWith(term))
                .Select(a => new { id = a.AUTHOR_ID, name = a.FULL_NAME});

            return Json(authors, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
        }

Javascript/Jquery

  $("#authorlist").tokenInput('/author/getauthors/' + $(this).val(), {
        hintText: "Select Authors",
        searchingText: "Searching..."
    });

I would have preferred to the JQuery in a more MVC way by actually callling data-autocomplete value and triggering the ActionResult that way, but I was getting lost, as you can see:

$("#authorlist").tokenInput($(this).attr("data-autocomplete"), {
        hintText: "Choose authors"        
    });

Can anyone help?


Solution

  • The problem is with your url building, because TokenInput uses the query parameter q by default but in your action you are using term.

    You have two oprions:

    Change the action signature:

    public ActionResult GetAuthors(string q)
    {
    }
    

    Configure TokenInput:

    $("#authorlist").tokenInput($(this).attr("data-autocomplete"), {
            queryParam: 'term',
            hintText: "Choose authors"        
        });