通过Api
调用Ajax
方法。在解析和其他必要的事情完成后,我得到以下结果。
["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);
}
});
});
从Json
方法返回的 GetPostcodesWithin
数据显示在顶部,并传递到SearchResult
答案 0 :(得分:1)
首先需要将方法更改为
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) {
....
}
})
postcode
方法中的参数SearchResult()
将包含数组中的3个字符串值。
因为您现在拥有一组字符串,所以您的查询现在需要
var posts = db.Posts.Where(p => postcode.Contains(p.PostCode));
旁注:您的第二个值包含可能需要修剪的空格("EF "
)?