Filip Huysmans
Filip Huysmans

Reputation: 1341

Extra param from jquery autocomplete to mvc controller

I require some help with my JQuery autocomplete. Im trying to autocomplete postalcodes filtered by countries but for this I need to send a country value along with the autocomplete term to my mvc controller.

The value of the var country should be send as an extra param towards the controller action but I can't seem to accomplish this.

Here is my setup without the extra param:

View:

@Html.TextBoxFor(j => j.MainAddressCountry, new { data_autocomplete_url = Url.Action("AutoCompletePostalCode", "Location")})

script:

var country = $("#MainAddressCountry");

$('*[data-autocomplete-url]')
    .each(function() {
        $(this).autocomplete({
            source: $(this).data("autocomplete-url"),
            messages: {
                noResults: '',
                results: function() {
                }
            },
            focus: function() {
                var menu = $(this).data("uiAutocomplete").menu.element;
                var focused = menu.find("li:has(a.ui-state-focus)");
                if (menu.parent().hasClass('scroll-wrapper')) {
                    setTimeout(function() {
                        var height = menu.parent().height();
                        if (focused.position().top + focused.height() > height) {
                            menu.scrollTop(menu.scrollTop() + parseInt(focused.position().top) + focused.height() - height);
                        }
                    }, 1);
                }
            },
            "open": function() {
                var menu = $(this).data("uiAutocomplete").menu.element;
                menu.addClass('scrollbar-dynamic').addClass('autocomplete-scroll');
            }
        });
    }
);

controller:

public ActionResult AutoCompletePostalCode(string term)
    {
        var items = new[] {"2220", "2222", "1800", "1900", "3541", "5214", "9000", "9002", "9006"};

        var filteredItems = items.Where(
            item => item.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) >= 0
            );
        return Json(filteredItems, JsonRequestBehavior.AllowGet);
    }

Anyone that might know how to do the trick?
Thanks in advance.

Upvotes: 0

Views: 754

Answers (1)

Cosmin
Cosmin

Reputation: 2214

You need to change the way you build source property into something like this:

 source: function(request, response) {
    $.getJSON("url here", { parameter1: 'your first parameter', parameter2: 'your second parameter' }, 
              response);
  },

Controller action:

public JsonResult Test(string parameter1, string parameter2)
{
 //code
}

Upvotes: 1

Related Questions