我试图在cshtml中构建一个自动完成文本框,我已经尝试了以下代码,但是它不起作用。控制器部分在调试期间没有错误,不确定我缺少哪一部分。感谢您的帮助。
[HttpPost]
public JsonResult Index(string Prefix)
{
//Note : you can bind same list from database
List<CardHolderDetails> ObjList = new List<CardHolderDetails>()
{
new CardHolderDetails {CardId=1,UnitNo="Latur" },
new CardHolderDetails {CardId=2,UnitNo="Mumbai" },
new CardHolderDetails {CardId=3,UnitNo="Pune" },
new CardHolderDetails {CardId=4,UnitNo="Delhi" },
new CardHolderDetails {CardId=5,UnitNo="Dehradun" },
new CardHolderDetails {CardId=6,UnitNo="Noida" },
new CardHolderDetails {CardId=7,UnitNo="New Delhi" }
};
//Searching records from list using LINQ query
var CityList = (from N in ObjList
where N.UnitNo.StartsWith(Prefix)
select new { N.UnitNo });
return Json(CityList, JsonRequestBehavior.AllowGet);
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#UnitNo").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/Index",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.UnitNo, value: item.UnitNo };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
</script>
@using (Html.BeginForm())
{
<div class="form-group">
@Html.EditorFor(model => model.UnitNo, new { htmlAttributes = new { @class = "form-control", id = "UnitNo" } })
</div>
}
返回的值未以自动完成形式显示。