如何将多个参数传递给MVC控制器,包括字符串列表/数组?

时间:2016-10-07 12:59:15

标签: jquery ajax asp.net-mvc

我有一个ajax调用,我正在尝试将一个字符串数组,以及一个id和搜索参数发布到控制器。有谁能告诉我怎么做? 例如:

的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);
        }
    });
});

控制器

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

当我尝试这个时,控制器上的 alreadyAddedReferralIds 总是为空。

3 个答案:

答案 0 :(得分:2)

尝试使用单个对象参数替换控制器中的参数。所以你会有类似的东西:

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; }
}

根据我的经验,发布到需要多个参数的操作方法时,不会填充其值。

答案 1 :(得分:1)

问题是因为您将alreadyAddedReferralIds作为对象传递。它应该是一个数组。试试这个:

var values = $(".referralIdList").map(function () {
    return this.id.split('referralId')[1];
}).get();

$.ajax({
    url: url,
    data: { 
        searchTypeId: searchTypeId, 
        searchParameter: searchParameter, 
        diaryId: diaryId, 
        alreadyAddedReferralIds: values // note: passing the array directly
    },
    cache: false,
    type: "POST",
    success: function (result) {
        if (result.success) {
            $("#searchResultsPlaceHolder").html(result.view);
        }
    },
    error: function (responseText, textStatus, errorThrown) {
        alert('Error - ' + errorThrown);
    }
});

另请注意,使用map()创建数组而不是each()

答案 2 :(得分:-1)

if (dialogName == 'link') {
    // Remove the 'Advanced' and 'Target' tabs from the 'Link' dialog.        
    dialogDefinition.removeContents('advanced');
    dialogDefinition.removeContents('target');

    // Get a reference to the 'Link Info' tab.
    var infoTab = dialogDefinition.getContents('info');

    // Remove unnecessary widgets from the 'Link Info' tab.         
    infoTab.remove('linkDisplayText');
}