Reputation: 161
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.
Upvotes: 1
Views: 3064
Reputation: 1154
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:
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)
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 };
}
Upvotes: 0
Reputation: 67296
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 );
}
});
Upvotes: 2