简体   繁体   中英

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. I am getting the below 404 console error. 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

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({
            type: "GET",
            url: "../Clients/VolDashboard/getViewsAssigned?" + $.param({ candidateIds: populateSelectedCandidateIds() }),
            success: Success,
            error: Errors
        });

Try pass parameters via data property:

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. According to your url, you're just sending an int (which can be converted to a single long ). The problem is that it isn't a collection, so it is unable to find the route. The 404 HTTP code is correct.

In this situation where you're URL encoding the list, your best bet would probably be to pass it as a string.

$.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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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