Reputation: 93
I'm using jQuery autocomplete plugin from jQuery website calling the controller url which return json in return. The problem is the parameter sent to the controller is always null.
Here is the in-browser jQuery code for the autocomplete:
$(document).ready(function() {
var url = "/Building/GetMatchedCities";
$("#City").autocomplete(url);
});
and here is the ASPNET MVC controller signature in C#:
public JsonResult GetMatchedCities(string city)
{
..
return this.Json(query, JsonRequestBehavior.AllowGet);
}
Thanks in advance,
Mohammad
Upvotes: 8
Views: 6309
Reputation: 1088
I had this same problem. After looking at the URL created by JQuery in Fiddler, I discovered that it looked like this: /MyController/MyMethod?term=x. So I changed my method signature to use the parameter name 'term' instead of 'q' ('q' is shown in the JQuery website autocomplete examples.). This fixed the problem and I was able to still return the JsonResult I needed.
public JsonResult MyMethod(string term)
{
...
return Json(query, JsonRequstBehavior.AllowGet);
}
Upvotes: 9
Reputation: 15401
Try adding the city data as extraParms:
$("#City").autocomplete(url, {
extraParams: { city: $('#City').val() }
});
This is assuming the $('#City') is an input of type text when using the .val
Based on your feedback the answer is:
The controller should be:
public JsonResult GetMatchedCities(string q)
{
..
return this.Json(query, JsonRequestBehavior.AllowGet);
}
The jquery would be:
$(document).ready(function() {
var url = "/Building/GetMatchedCities";
$("#City").autocomplete(url);
});
Upvotes: 4
Reputation: 192457
When I did this, I specified the source
option on autocomplete to be a function that called out to the ASPNET app. This allowed me to specify the URL directly. For you it would like this:
$("#City").autocomplete({
source: function(req, responseFn) {
addMessage("search on: '" + req.term + "'<br/>", true);
$.ajax({
url : ajaxUrlBase1 + "GetMatchedCities/" + req.term,
cache : false,
type : "GET", // http method
success : function(msg){
// ajax call has returned
var result = msg;
if (result !== null){
var a = [];
for(var i=0; i < result.length; i++) {
a.push({label: result[i].cityname, id: result[i].abbrev});
}
responseFn(a);
} else {
responseFn(null);
}
}
});
}
});
Of course, what you do inside the success
fn would depend on the shape of the json you return from your Action.
Upvotes: 2