1

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.

4
  • Where is the variable name in your url in your ajax method? Commented Nov 24, 2015 at 20:43
  • 1
    Have you tried using $.ajax({ ... data: values }) instead of stringifying them? I'm pretty sure jQuery will encode the parameters for you. Commented Nov 24, 2015 at 20:45
  • show DataViewModel and the {collection of values} code. @Pluto has the correct advice in the comment above. Commented Nov 24, 2015 at 20:47
  • Yeah we definitely need to see the full model or an example of the data you're sending to the server. While jQuery can easily convert basic values in an object to be included in a request, having nested objects could be problematic. Some of your data in values.Values might not be sent. Commented Nov 24, 2015 at 20:53

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.