1

I am using the jquery ui autocomplete in MVC 4 with Razor HTML. I am able to use it ok with hard coded values but I was wondering how I can connect it to the database so the the values coming up don't have to be hard coded.

2
  • Please rephrase your question. Now you ask, how do I program, this is not doable in any scenario. You could try nerddinnerbook.s3.amazonaws.com/Intro.htm for more info. Commented Mar 24, 2013 at 22:57
  • I'm pretty sure that autocomplete takes a url parameter. If you point this at a server that returns a list, then you are good to go. docs Commented Mar 24, 2013 at 22:57

2 Answers 2

2

If you are using MVC4, then you should have an action created that you can access from the view (render the action url). Then, you need to set this (url) as the source when setting up the autocomplete jquery.

The documentation for a remote source is here.

For MVC, it would look something like this:

$( "#birds" ).autocomplete({
      source: "/MyController/OptionsAction",
      minLength: 2,
      select: function( event, ui ) {
        log( ui.item ?
          "Selected: " + ui.item.value + " aka " + ui.item.id :
          "Nothing selected, input was " + this.value );
      }
    });
Sign up to request clarification or add additional context in comments.

Comments

0

Its better to use MVC's @URL.Action to ensure the URL is encoded correctly even if your view is one or ten folders deep.

In the above example "/MyController/OptionsAction", would not work if you moved your view one folder down where as @URL.Action would continue to work.

Note the format of the ajax call is like this:

  1. Sending data:

url (where you are posting to)

data (the data you are posting)

type (the type of request being made: POST or GET or PUT. Default if left blank is GET)

contentType (content type to use when sending data to the server. Better not to change unless necessary)

  1. Receiving data:

dateType (the datatype you are expecting back: in this case json)

success (function called if the request succeeds)

        $('#Country').autocomplete({
        source: function (request, response) {
            $.ajax({
                url: '@Url.Action("GetCountries", "User")',
                data: "{ 'CountrySearch': '" + $('#Country').val() + "' }",
                dataType: "json",
                type: "POST",
                contentType: 'application/json',
                success: function (data) {
                    response($.map(data, function (item) {
                        return JSON.parse(item);
                    }))
                },
                error: function (jqXhr, textStatus, errorThrown) { alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')"); },
            })
        },
        minLength: 1,
    });

Where countries returns data from a database call like this:

{ "Countries":"["Australia", "Austria", "Canada", "United States"]" }

    public JsonResult GetCountries(string CountrySearch)
    {
        string[] Countries = new AddressManager().GetCountries(CountrySearch);
        string serialisedList = new JavaScriptSerializer().Serialize(Countries);
        return new JsonResult { Data = new { Countries = serialisedList }, ContentEncoding = Encoding.UTF8, ContentType = "text/plain", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.