kibowki
kibowki

Reputation: 4376

How to handle parameters on C# server side sent from jQuery POST?

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?

Upvotes: 0

Views: 321

Answers (1)

David L
David L

Reputation: 33823

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

Upvotes: 1

Related Questions