有一个通过Ajax
调用的Api
方法。在解析和其他必要的事情完成之后,我得到了以下结果:
["IG4","E1 ","E16"]
一旦收到结果,它调用另一个MVC ActionResult
来显示来自数据库的数据,其中对象的邮政编码属性包含这些Json
结果之一。然而,它不工作。
public ActionResult SearchResult(JsonResult postcode)
{
var posts = db.Posts.Where(p => p.PostCode.Contains(postcode));
return PartialView("postlist", posts);
}
当ActionResult
通过Ajax
被调用时,我检查了url
被调用的内容,得到了以下结果
SearchResult?postcode%5B%5D=IG4&postcode%5B%5D=E1+&postcode%5B%5D=E16
$('#searchBtn').on('click', function () {
var _postcode = $('#searchPostcode').val();
var _distance = $('#searchDistance').val();
alert("postcode " + _postcode + " distance " + _distance);
var _url = '@Url.Action("GetPostcodesWithin", "Api/PostcodeApi")'; // don't hard code url's
$.ajax({
type: "GET",
url: _url,
data: { postcode: _postcode, distance: _distance },
success: function(data) {
alert("search ok");
$.ajax({
type: "GET",
url: '@Url.Action("SearchResult", "Posts")',
data: { postcode: data },
success: function (data) {
alert("Post results called");
$("#postList").html(data).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
GetPostcodesWithin
方法返回的Json
数据显示在顶部,传递给SearchResult
首先需要将方法更改为
public ActionResult SearchResult(IEnumerable<string> postcode)
然后将第二个ajax调用更改为
$.ajax({
type: "GET",
url: '@Url.Action("SearchResult", "Posts")',
data: { postcode: data },
traditional: true, // add this
success: function (data) {
....
}
})
SearchResult()
方法中的参数postcode
将包含数组中的3个字符串值。
因为你现在有一个字符串集合,你的查询现在需要是
var posts = db.Posts.Where(p => postcode.Contains(p.PostCode));
旁注:你的第二个值包含一个空格("EF "
),可能需要修剪?