0

So I'm trying to send the following data from jQuery on the server side like so:

var fd = new FormData();
fd.append('name', 'tyler');
fd.append('hello', 'world');
$.post('/NMISProduct/Index', { submitData: fd}, function(returnedData) {
            console.log(returnedData);
}, 'json');

How do I handle this on the server side? Here is what I have, which I'm sure is very wrong:

[HttpPost]
public string Index(string submitData)
{
    return submitData;
}

I just want to return what I send to C# back to jQuery so I know it got there. What am I doing wrong?

kibowki
  • 4,206
  • 16
  • 48
  • 74

1 Answers1

1

Your current approach ties you to FormData() and it doesn't take advantage of JSON.Net which is happy and eager to deserialize your object so that you can consume it.

If you truly want to test "full-loop", deserialize to a strongly typed object and return it back to the client as serialized json, building out the matching object on the client instead of using FormData().

$.post('/NMISProduct/Index', { name: 'tyler',hello: 'world' }, function(data) {
    console.log(data);
});

[HttpPost]
public ActionResult Index(FormData submitData)
{
    return Json(submitData);
}

public class FormData 
{
    public string Name { get; set; }
    public string Hello { get; set; }
} 
David L
  • 32,885
  • 8
  • 62
  • 93
  • _"What you have technically works"_. No it doesn't (it will throw an _Uncaught TypeError: Illegal invocation_ error) because posting `FormData` requires explicitly setting the `processData: false,` and `contentType: false,` ajax options. Based on the code you have shown (which is the correct approach), the script needs to be `$.post('/NMISProduct/Index', { name: 'tyler',hello: 'world' }, function() {` –  Jun 24 '15 at 00:14
  • @StephenMuecke It didn't even occur to me that it was THE FormData object. Thank you for pointing it out. I've updated my answer to reflect your comments. – David L Jun 24 '15 at 02:59
  • Thanks for the answer guys - unfortunately, I am tied to using the official JS `FormData` object as that is the only way you can upload files via AJAX (which is what I need to do), unless that isn't actually the case. I'm basing this knowledge from this question: http://stackoverflow.com/questions/2320069/jquery-ajax-file-upload – kibowki Jun 24 '15 at 13:18
  • Then you need to use `$.ajax()` (not `$.post()`) so that you can set the correct options. Suggest you also look at [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681) –  Jun 25 '15 at 01:24