C. Daniel
C. Daniel

Reputation: 141

Passing parameters to MVC controller via JavaScript AJAX GET

I am trying to pass a collection of data to my C# controller via AJAX from JavaScript. The data being passed will not always be the same. There is no create/update/delete to the system happening at all this is purely a read operation.

My object looks like this:

values = {
    Id: [SOME INT ID],
    DB: [SOME DB ID],
    Values: [{collection of values}]
}

This is my ajax call:

$.ajax({
    url: "MYURL?" + encodeURIComponent(JSON.stringify(values)),
    type: "GET",
    success: function(data){
        // do callback stuff
    },
    dataType: "json"
});

My controller is:

[HttpGet]
public ActionResult MyController(DataViewModel viewModel){
    // Stuff and Things code
}

The data is not being populated in the controller in the viewModel at all. All the values are null. How can I pass the JSON data into the controller? Thank you in advance.

Upvotes: 1

Views: 1048

Answers (1)

Pluto
Pluto

Reputation: 3026

Your ajax call should be the following instead:

$.ajax({
    url: "MYURL",
    type: "GET",
    success: function(data){
        // do callback stuff
    },
    data: values
});

Some issues that existed in your code include that you used a semi-colon instead of a comma at the end of the url: line and dataType: sets the response data type (not the request data type, which is sent to the server).

Upvotes: 2

Related Questions