1

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.

3
  • 1
    And why do you send it as JSON? Commented May 28, 2012 at 21:40
  • Because I eventually want to use the same code to send more structured data, containing recursively defined js objects. JSON seems like a better fit than name-value pairs. Commented May 29, 2012 at 9:58
  • Related/dupe of: stackoverflow.com/questions/5473156/… stackoverflow.com/questions/5022958/… Commented Jan 7, 2013 at 10:14

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.