0
我試圖自動完成下拉列表,當有人鍵入一個郵政編碼到輸入字段,但我還沒有能夠填充下拉列表,但這是我在哪裏上午:我如何自動完成在MVC中使用ajax的下拉列表
JQuery的
<script type="text/javascript" language="javascript">
//<![CDATA[
// have we had at least 3 characters typed in?
var searchTextTrigger = false;
$(document).ready(function() {
$('#postcodeSearch').focus();
});
// 0m0_uk
$(function() {
var content = $('#postcodeSearch').val();
$('#postcodeSearch').keyup(function() {
// have we had at least 3 characters in our text box
if ($('#postcodeSearch').val().length >= 3) {
// yes, so after this point even if we have less it will still send the request
searchTextTrigger = true;
}
if ($('#postcodeSearch').val() != content && searchTextTrigger == true) {
content = $('#postcodeSearch').val();
var searchText = $('#postcodeSearch').val();
alert(searchText);
$.ajax({
url: "/Stores/AutocompleteSuggestions/" + etaleEncode(searchText),
success: function (data) {
$("#ajaxPostCodeList").html("");
for (var i = 0; i < data.length; i++) {
var item = data[i];
$('#ajaxPostCodeList').append($("<option></option>").val(item.Code).html);
}
},
error: function() {
alert("an error occured");
}
});
}
});
});
//]]>
</script>
和形式:
<input id="postcodeSearch" name="postcodeSearch" type="text" />
<select id="ajaxPostCodeList">
</select>
腳本以下部分不工作:
success: function (data) {
$("#ajaxPostCodeList").html("");
for (var i = 0; i < data.length; i++) {
var item = data[i];
$('#ajaxPostCodeList').append($("<option></option>").val(item.Code).html);
}
},
控制器
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult AutocompleteSuggestions(string searchText)
{
var sTerm = searchText;
if (!String.IsNullOrEmpty(searchText))
{
sTerm = Decode(searchText);
}
var suggestions = _postcodeRepository.GetAutoCompleteSearchSuggestion(sTerm);
return Json(suggestions.ToList());
}
所以搜索文本正常傳遞到控制器。但我不知道怎麼辦的就是填寫的下拉與值列表。
任何幫助非常感謝!
我需要改變我的控制器,以便它有公共JsonResult和JsonRequestBehavior.AllowGet);謝謝 – anna