1

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 ''
Tsukasa
  • 6,342
  • 16
  • 64
  • 96
  • Why do you have to use JSON? It seems an unnecessary complication. `x-www-form-urlencoded` is pretty standard - especially for non-AJAX requests – Rory McCrossan Nov 02 '16 at 17:19
  • @RoryMcCrossan can you provide an example? This is being submitted via ajax. The controller can't use a predefined model because the inputs are unknown to the controller. The data being sent is using the ID of the input as the key. – Tsukasa Nov 02 '16 at 17:23
  • You're calling JSON.stringify on a string (the result of [`serialize`](http://api.jquery.com/serialize/)). Thus, when you parse the JSON, it returns a string, as the error says. See [Convert form data to JavaScript object with jQuery](http://stackoverflow.com/q/1184624/215552) for how to make an object from form data. – Heretic Monkey Nov 02 '16 at 17:23
  • @MikeMcCaughan if I take away JSON.stringify I then get `Unexpected character encountered while parsing value: _. Path ''` – Tsukasa Nov 02 '16 at 17:26
  • `The controller can't use a predefined model because the inputs are unknown to the controller.` Why not just loop through the `Request.Params` then? – Rory McCrossan Nov 02 '16 at 17:27
  • @Tsukasa Did you read the question and answers in that link? Because then you would see how to send an object. – Heretic Monkey Nov 02 '16 at 17:29

1 Answers1

1

Couple of better options:

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

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202