Chris Becke
Chris Becke

Reputation: 36016

Passing unstructured JSON between jQuery and MVC Controller Actions

There is quite a lot of helpful information on MVC model binding. My problem stems from the fact that I am trying to avoid creating strongly typed data in my MVC application as it mostly needs to act as a data router.

Basically, I have a set of fields on a page, with a class 'input', that I can gather with jQuery('.input'), iterate over and stuff into a javascript object. I then send this to my ASP.NET MVC controller:

var inputData = my_serialize( $('input');
$.ajax({
  type:'POST',
  url: '/acme/Ajax/CaptureInput',
  dataType: "json",
  data: { inputData: JSON.stringify(inputData) },
  success: Page_Response_RegisterAndDeposit,
  error: Page_AjaxError
});

On the C# side, I have

public JsonResult CaptureInput(string inputDataAsJsonString)
{
  JavaScriptSerializer JSON = new JavaScriptSerializer();
  object inputData = JSON.DeserializeObject(inputDataAsJsonString);

This seems like a wasteful level of indirection, I'd prefer to pass the data as contentType:application/json and have CaptureInput accept an object or IDictionary or even a dynamic.

Upvotes: 1

Views: 2212

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

You could use the serializeArray method. Let's suppose that you have a form containing the input elements which could be of any type and you want to invoke the following controller action:

public ActionResult CaptureInput(Dictionary<string, string> values)
{
    ...
}

here's how you could proceed:

<script type="text/javascript">
    var values = $('form').serializeArray();
    var data = {};
    $.each(values, function (index, value) {
        data['[' + index + '].key'] = value.name;
        data['[' + index + '].value'] = value.value;
    });

    $.ajax({
        url: '@Url.Action("CaptureInput")',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(data),
        success: function (result) {
            alert('success');
        }
    });
</script>

Upvotes: 1

Martin Bayly
Martin Bayly

Reputation: 2503

Not exactly what you're after but maybe the resolution of this issue would give you a partial workaround, by allowing you to bind to a simple wrapper object with an embedded Dictionary. It might even allow binding direct to a Dictionary. Not sure... You might also need to explicitly set the json ContentType header in your $.ajax call

"JSON model binding for IDictionary<> in ASP.NET MVC/WebAPI"

Upvotes: 0

Related Questions