Tsukasa Tsukasa - 1 month ago 19
C# Question

Pass form as json to controller and parse

I have dynamically generated forms so I need to handle an unknown amount of inputs being passed to the controller. There can be no predefined model (I assume) to handle this so I figure sending a json string might be best.

The problem is parsing the json in the controller to JObject.

Here is what I'm using before submitting with an ajax request.

var json = JSON.stringify($(this).serialize());


now the string passed to the controller looks as follows

"\"__RequestVerificationToken=FGhUgZXRTWcDqC-ffeMb7S2paAgFSUN4XyJl72qu85TD1GPpi69aGiyHzXBfHpb6XgBrGXAhtJz6NWka0XGK_JRSqpm-Q41tiYvJe1NO3J-_4leHroUvDp3VsWYMLFMm0&Form.ID=d7025ad7-745b-4898-ad40-350ef1d511ec&a5fbdde8-4c34-48e2-9a77-083c31eb1ae1=This+is+a+test\""


In the controller

JObject jo = JObject.Parse(json); //error

foreach (var o in jo)
{
string key = o.Key;
JToken val = o.Value;
}


The error i'm getting

"Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path ''

Answer

Couple of better options:

The Ajax data: payload is then just your $(this).serialize()