goldfinger
goldfinger

Reputation: 1115

posting JSON to MVC controller - String parameter is null

I am intentionally trying NOT to use a binding in the controller parameter, so I have a controller that looks like:

 [HttpPost]
        public ActionResult UntypedForm(String serializedformdata)
        {
        //// ...
        }

When I post serialized JSON form elements to the controller with the below code:

var formelements = $('#form').serializeArray();
$.post(url, formelements, function (data) {

    }, "json").error(function () {
        alert("Error posting to " + url); 
    });

I get a NULL value for String serializedformdata on my controller. However, when I replace String serializedformdata with a strongly-typed object, binding works properly as expected.

The whole point of my controller is generic JSON posts, where I will create a BSON document to place into a Mongo database. SO....I intentionally DO NOT want model binding and I want the serialized string as pamameter. Why is my serializedformdata string null when I post?

Note - I also tried to bind to Dictionary with

public ActionResult UntypedForm(Dictionary<string,string> serializedformdata)
            {
            //// ...
            }

but serializedformdata is still null.

Upvotes: 1

Views: 2854

Answers (1)

McGarnagle
McGarnagle

Reputation: 102753

The function serializeArray creates a Javascript object with the form's key/value pairs. You don't want that, you want a single key/value with serializedformdata = (JSON string). Ie, like this;

var formelements = { serializedformdata: JSON.stringify($('#form').serializeArray()) };

This passes the raw JSON string to the controller's parameter. You can use the JavaScriptSerializer to get the object on the server:

var obj = (List<Dictionary<string,string>>)new JavaScriptSerializer().Deserialize(serializedformdata, typeof(List<Dictionary<string,string>>));
Dictionary<string,string> dict = obj.First();
string someval = dict["somekey"];

Upvotes: 2

Related Questions