I am trying to implement auto complete however I'm finding that it is not passing the partial string, I'm using MVC3, the razor view engine and jquery to put it all together.
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/base/jquery-ui.css" type="text/css" media="all" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"> </script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"> </script>
<script type="text/javascript">
$(function (request) {
alert("test:" + $("#searchTerm").val());
$("#searchTerm").autocomplete({
source: "/Home/GetAccounts/" + $("#searchTerm").val(),
type: 'POST',
dataType: 'json',
data: request.term,
minLength: 3,
select: function (event, ui) {
window.location.href = 'Home/GetAccounts/' + ui.item.value;
}
});
});
</script>
@using (Html.BeginForm())
{
<form method="post" action=""&开发者_Go百科gt;
<input id="searchTerm" name="searchTerm" type="text" />
<input type="submit" value="Go" />
</form>
}
And Below is the Controller
public ActionResult GetAccounts(string id)
{
var accounts = NavRepository.GetAccountsBasedOnString(id);
var accountStrings = new string[accounts.Count];
var count = 0;
foreach (var account in accounts)
{
accountStrings[count] = account.AccountID;
count++;
}
return Json(accountStrings, JsonRequestBehavior.AllowGet);
}
I did hunt around a few places (such as http://jqueryui.com/demos/autocomplete/#remote-jsonp ) including here but I just can't seem to crack this one.
Additional Here is how I write my routes.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
And as noted in the comments if i set value="test" for searchTerm it only sends this string
The problem is that when you set the source of your autocomplete it takes the value of the textfield at the moment this is done (i.e. at DOM load) => the value is empty at this stage. The document.ready event handler doesn't take a request object.
You could pass a function to the source
property when wiring your autocomplete:
$(function() {
$('#searchTerm').autocomplete({
source: function(request, response) {
$.ajax({
url: '@Url.Action("GetAccounts", "Home")',
data: { id: request.term },
dataType: 'json',
type: 'POST',
minLength: 3,
select: function (event, ui) {
window.location.href = '@Url.Action("GetAccounts", "Home")' + ui.item.value;
}
});
});
});
精彩评论