简体   繁体   English

对C#控制器操作的Ajax调用不起作用

[英]Ajax call to C# controller action not working

For some reason I am not able to pass a list of id's into my controller action using my AJAX request. 由于某种原因,我无法使用AJAX请求将ID列表传递到控制器操作中。 I am getting the below 404 console error. 我收到以下404控制台错误。 Can anyone tell me why this is happening? 谁能告诉我为什么会这样吗?

Error 错误

Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:8088/Clients/VolDashboard/getViewsAssigned?candidateIds%5B%5D=177 无法加载资源:服务器以状态404(未找到)响应http:// localhost:8088 / Clients / VolDashboard / getViewsAssigned?candidateIds%5B%5D = 177

Controller Action 控制器动作

public JsonResult getViewsAssigned(List<long> candidateIds)
    {
        long clientId = webRequestState.ClientId.Value;
        long clientUserId = webRequestState.ClientUserId.Value;
        return Json(clientViewService.getViewsAssignedToCandidates(candidateIds, clientId, clientUserId), JsonRequestBehavior.AllowGet);
    }

AJAX Request AJAX请求

$.ajax({
            type: "GET",
            url: "../Clients/VolDashboard/getViewsAssigned?" + $.param({ candidateIds: populateSelectedCandidateIds() }),
            success: Success,
            error: Errors
        });

Try pass parameters via data property: 尝试通过data属性传递参数:

var data = populateSelectedCandidateIds();
$.ajax({
type: "GET",
data: {candidateIds: data},
url: "../Clients/VolDashboard/getViewsAssigned",
success: Success,
error: Errors  
});  

You can also see accepted answer here to get main idea. 您也可以在此处查看已接受的答案以了解主要思想。

The problem is that your C# method is expecting a List<long> as the parameter type. 问题是您的C#方法期望使用List<long>作为参数类型。 According to your url, you're just sending an int (which can be converted to a single long ). 根据您的网址,您只是发送一个int (可以将其转换为单个long )。 The problem is that it isn't a collection, so it is unable to find the route. 问题在于它不是集合,因此无法找到路线。 The 404 HTTP code is correct. 404 HTTP代码正确。

In this situation where you're URL encoding the list, your best bet would probably be to pass it as a string. 在这种情况下,您对列表进行URL编码,最好的选择是将其作为字符串传递。

$.ajax({
    type: "GET",
    url: "../Clients/VolDashboard/getViewsAssigned?" + 
            $.param({ candidateIds: 
               populateSelectedCandidateIds().toString() 
            }),
    success: Success,
    error: Errors
});

Then you would need to adjust your C# method like this: 然后,您需要像这样调整C#方法:

public JsonResult getViewsAssigned(string candidateIds)
{
    List<long> idList = candidateIds.Split(',').Select(long.Parse).ToList();
    long clientId = webRequestState.ClientId.Value;
    long clientUserId = webRequestState.ClientUserId.Value;
    return Json(clientViewService.getViewsAssignedToCandidates(idList, clientId, clientUserId), JsonRequestBehavior.AllowGet);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM