Sugafree Sugafree - 5 months ago 33
Ajax Question

Using a list of Json results as parameters for a mvc actionresult, to return objects from database with Linq and Lambda

There is an

Api
method called via
Ajax
. After parsing and other necessary things has been finished, I get the following result.

["IG4","E1 ","E16"]


As soon as the results received, it calls another
MVC ActionResult
to display data from the database, where the postcode attribute of the object contains one of these
Json
results. However it does not work.

public ActionResult SearchResult(JsonResult postcode)
{
var posts = db.Posts.Where(p => p.PostCode.Contains(postcode));
return PartialView("postlist", posts);

}


When the
ActionResult
is called via
Ajax
, I checked what
url
is being called and got the following result

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
data returned from
GetPostcodesWithin
method is displayed on the top, which is passed onto
SearchResult

Answer

You first need to change the method to

public ActionResult SearchResult(IEnumerable<string> postcode)

Then change the 2nd ajax call to

$.ajax({
    type: "GET",
    url: '@Url.Action("SearchResult", "Posts")',
    data: { postcode: data },
    traditional: true, // add this
    success: function (data) {
        ....
    }
})

The parameter postcode in the SearchResult() method will then contain the 3 string values from your array.

Because you now have a collection of strings, your query now needs to be

var posts = db.Posts.Where(p => postcode.Contains(p.PostCode));

Side note: Your second value contains a space ("EF ") which may need to be trimmed?