查看:
<script type="text/javascript">
$(document).ready(function () {
$("#OriginInput").autocomplete({
source: function (request, response) {
$.ajax({
url: '@Url.Action("AjaxMethod","MyUrl")', type: "POST", dataType: "json",
data: { id: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.label, value: item.id };
}));
}
});
},
minLength: 2
});
控制器
public static List<PostalCodeModel> ListOfPostalCode;
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult AjaxMethod(string x)
{
x = Request.QueryString["term"];
var locations = ListOfPostalCode.Where(r => x != null && (r.City.StartsWith(x) || r.State.StartsWith(x) || r.Zip.StartsWith(x) || r.Country.StartsWith(x))).Take(25).Select(r => new { id = r.ToString(), label = r.ToString(), name = r.ToString() });
return Json(locations, JsonRequestBehavior.AllowGet);
}
模型
public class PostalCodeModel
{
public PostalCodeModel(string c, string s, string z, string o)
{
City = c;
State = s;
Zip = z;
Country = o;
}
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
public override string ToString()
{
// trim to remove unnecessary spaces
return City.Trim() + ", " + State.Trim() + ", " + Zip.Trim() + ", " + Country.Trim();
}
每次我在“自动完成”框中进行此调用时,x在我的Controller中返回null,因此不会解析邮政编码列表中的任何信息。不会包含初始化Controller中邮政编码的完整列表的查询(该列表的大小约为190000左右),但似乎工作正常。
我认为主要问题是视图中的ajax没有将“ OutputText”框传递给请求/响应,但是在其他地方搜索时似乎找不到问题。感谢您提供的所有帮助;一周前才刚开始使用JavaScript。
答案 0 :(得分:1)
在ajax方法中,您发送的数据错误。应该是这样的。
$.ajax({
url: '@Url.Action("AjaxMethod", "MyUrl")',
type: "POST",
data: { term: request.term },
dataType: "json",
success: function (data) {
response($.map(data, function (item) {
return { label: item.label, value: item.id };
}));
}
});
此外,您无需使用Request.QueryString["term"];
来获取参数
更改
public JsonResult AjaxMethod(string x)
到
public JsonResult AjaxMethod(string term)
也不要忘记使检查项为空。