necrofish666 necrofish666 - 2 months ago 6
Ajax Question

How to pass multiple parameters to MVC controller including list/array of strings?

I have a ajax call and I'm trying to post an array of strings, as well as an id and search parameter to a controller. Anyone able to show me how to do this?
Example:

jQuery

$("body").on("click", "#btnClientModalSearch", function (e) {
preventDefaultAction(e);
var url = GetUrlPath() + "/Client/GetClientCalendarSearchResults";
var searchTypeId = $("#ddlSearchType").val();
var searchParameter = $("#tbSearchParameter").val();
var diaryId = $("#SelectedEventId").val();
var values = [];
$(".referralIdList").each(function () {
var referralId = $(this).attr("id");
var arr = referralId.split('referralId');
values.push(arr[1]);
});
var postData = { alreadyAddedReferralIds: values };
$.ajax({
url: url,
data: { searchTypeId: searchTypeId, searchParameter: searchParameter, diaryId: diaryId, alreadyAddedReferralIds: postData },
cache: false,
type: "POST",
success: function (result) {
if (result.success === true) {
$("#searchResultsPlaceHolder").html(result.view);
}
},
error: function (responseText, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
}
});
});


Controller

public JsonResult GetClientCalendarSearchResults(string searchTypeId, string searchParameter, string diaryId, List < string > alreadyAddedReferralIds) {}


When I try this, the alreadyAddedReferralIds is always empty at the controller.

Answer

Try replacing the parameters in the controller with a single object parameter. So you would have something like:

public JsonResult GetClientCalendarSearchResults(SearchResultsRequest request)

public class SearchResultRequest
{
   public string searchTypeId { get; set; } 
   public string searchParameter { get; set; } 
   public string diaryId { get; set; } 
   public List<string> alreadyAddedReferralIds { get; set; }
}

From my experience posting to an action method that requires multiple parameters won't have their values populated.