views:

2617

answers:

2

I know this issue has been touched on before eg here

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 firugre out how to access the array in my controller method (AjaxUpdate)

A: 

Check out this link It may be helpful to you!

Vikas
+6  A: 

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.

swilliams
Thanks for a great answer.I ended up using the stringify function + JavaScriptSerializer
Rasmus