4

I know this issue has been touched on before, e.g. here:

How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

But the solutions doesn't seem to fit my problem.

Here is my HTML. The number of rows are variable:

 <table id="workPlanTable">
    <tr>
        <th>
            Begin
        </th>
        <th>
            End
        </th>
    </tr>

    <tr itemId="1">
        <td><input class="begin" id="begin_1" name="begin_1" type="text" value="5:30" /></td>
        <td><input class="end" id="end_1" name="end_1" type="text" value="11:30" /></td>
    </tr>
    <tr itemId="3">
        <td><input class="begin" id="begin_3" name="begin_3" type="text" value="5:30" /></td>
        <td><input class="end" id="end_3" name="end_3" type="text" value="7:30" /></td>
    </tr>

</table>

The JS builds an array of objects and posts them to a control method:

<script type="text/javascript">
$(function() {

  submitForm = function() {
    var items = new Array();
    $("#workPlanTable tr").each(function(i) {
      var end = $(this).find(".end").val();
      var begin = $(this).find(".begin").val();
      var item = {
        "Begin": begin,
        "End": end
      };
      items.push(item);

    });
    var postData = {
      myItems: items
    };

    $.ajax({
      url: '~/WorkPlan/AjaxUpdate',
      type: 'POST',
      dataType: 'json',
      data: postData,
      contentType: 'application/json; charset=utf-8',
      success: function(result) {
        alert(result.Result);
      }
    });
  }
})
</script>

Each row represent a WorkPlanItem that.

My goal is to post them all to my controller to update them.

I can't seem to figure out how to access the array in my controller method (AjaxUpdate).

1 Answer 1

7

You can serialize the form as Vikas posted, or you could use a stringify function if you'd prefer to walk the page (as you are currently doing) and use the postData array.

On the controller, you'll need to handle the json string. You can use the System.Web.Script.Serialization.JavaScriptSerializer class to deserialize it. If you have an object that maps to the data you're passing, you can use the Deserialize method. If you don't, you can still use DeserializeObject, however that gives you a Dictionary<string, string> collection that you'll have to walk through to get your data. Not exactly fun (trust me), but it works.

1
  • Thanks for a great answer. I ended up using the stringify function + JavaScriptSerializer
    – Rasmus
    Commented Apr 21, 2009 at 7:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.