使用Json结果列表作为mvc actionresult的参数,使用Linq和Lambda从数据库返回对象



有一个通过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 "),可能需要修剪?

最新更新