Say, for example, you wanted to fill jQuery autocomplete with a list of values based on the choice of another field so that you could not determine the data on the page load. Usually I call the action method in the call $.ajax, and then return an array of elements to populate autocomplete with.
: jQuery, , :
$(function() {
$.ajax({
url: '@Url.Action("GetHomes", "Account")',
type: "POST",
datatype: "json",
success: function (data) {
if (data.Success || data.Success == null) {
WireUpHomesData(data);
} else {
ShowErrorDialog();
}
}
});
ShowDialog();
});
function WireUpHomesData(data) {
var homes = new Array();
for (var i = 0; i < data.length; i++) {
homes[i] = { label: data[i].HomeName, text: data[i].HomeId, icon: data[i].HomeIcon, desc:data[i].HomeAddress };
}
$("#home").autocomplete({
source: homes,
select: function (event, item) {
homeUrl = '@Url.Action("Site", "Sites")/' + item.item.text;
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a><span class='" + item.icon + "'/><span class='fs-ui-autocomplete-home'>" + item.value + "</span><br>" + item.desc+ "</a>")
.appendTo(ul);
};
$(".ui-autocomplete").addClass("fs-ui-autocomplete");
}
:
public JsonResult GetHomes()
{
return Json(RequiresAclAttribute.HomesForUser());
}
, :
public IEnumerable<HomeInfo> HomesForUser()
HomeInfo:
public class HomeInfo
{
public string HomeId { get; set; }
public string HomeName { get; set; }
public string DisplayName { get; set; }
public string HomeAddress { get; set; }
public string HomeIcon { get; set; }
}