将Ajax阵列发送到Controller

时间:2013-03-16 08:27:42

标签: c# .net jquery asp.net-mvc-2

enter image description here

enter image description here

上面我展示了我的动态UI以及根据日期动态为相关字段设置id的方式。

所以我需要将这些数据作为数组ajax发送到MVC控制器中,然后在控制器中选择那些东西。当我点击保存按钮时,应该会发生这种情况

我的帖子方法如下(没有上面的数组细节):

 $("#clocked-details").find("#btnSave").die('click').live('click', function () {

       var yearValue = $("#year").val();
       var monthValue = $("#month").val();

       $.ajax({
          url: "/Employees/UpdateEmployeeClockedHoursByProvider",
          type: 'POST',
          cache: false,
          data: { employeeId: employeeId, year: yearValue, month: monthValue },
          success: function (result) {

          },
          error: function (xhr, ajaxOptions, thrownError) {
                 alert(xhr.status);
                 alert(thrownError);
               }
           });
          return false;
       });

我的控制器如下(没有jquery数组maupulation):

[HttpPost]
public void UpdateEmployeeClockedHoursByProvider(Guid employeeId, int year, int month)
        {

        }

更新

使用下面提到的代码生成UI:

<% foreach (var ec in Model)
       {%>
    <tr>
        <td>
            <%: ec.ClockedDate.ToString("yyyy-MM-dd") %>
        </td>
        <td>
            <input type="number" id="<%: ec.ClockedDate.ToString("yyyy-MM-dd") %>-hours" name="<%: ec.ClockedDate.ToString("yyyy-MM-dd") %>-hours"
                class="total-hours" placeholder="Hours" value="<%: ec.TotalHours %>" />
        </td>
        <td>
            <input type="number" id="<%: ec.ClockedDate.ToString("yyyy-MM-dd") %>-minutes" name="<%: ec.ClockedDate.ToString("yyyy-MM-dd") %>-minutes"
                class="total-minutes" placeholder="Minutes" value="<%: ec.TotalMinutes %>" />
        </td>
    </tr>
    <% }%>

我的问题:

  1. 如何使用ajax在每行数据上发送动态2个字段?

  2. 如何在控制器内操作该数组?

2 个答案:

答案 0 :(得分:2)

您可以首先在服务器上定义一个代表您要检索的数据的视图模型:

public class MyViewModel
{
    public Guid EmployeeId { get; set; }
    public int Year { get; set; }
    public int Month { get; set; }

    public ItemViewModel[] Items { get; set; }
}

public class ItemViewModel
{
    public int TotalHours { get; set; }
    public int TotalMinutes { get; set; }
}

然后让您的控制器操作将此视图模型作为参数:

[HttpPost]
public ActionResult UpdateEmployeeClockedHoursByProvider(MyViewModel model)
{
    ...
}

下一步是稍微修改一下您的视图,因为现在您似乎是硬编码输入字段而不是使用html帮助程序并为输入字段定义错误的ID和名称(在HTML id和{ {1}}属性不能以数字开头)。

所以在这里你可以如何生成表格:

name

最后你可以有一些javascript文件,它将订阅表单的<% using (Html.BeginForm("UpdateEmployeeClockedHoursByProvider", null, FormMethod.Post, new { id = "myForm" })) { %> <table> <thead> <tr> <th>Clocked Date</th> <th>Total Hours</th> <th>Total Minutes</th> <tr> </thead> <tbody> <% for (var i = 0; i < Model.Count; i++) { %> <tr> <td> <%= Html.DisplayFor(x => x[i].ClockedDate) %> </td> <td> <%= Html.TextBoxFor( x => x[i].TotalHours, new { type = "number", placeholder = "Hours", @class = "total-hours" } ) %> </td> <td> <%= Html.TextBoxFor( x => x[i].TotalMinutes, new { type = "number", placeholder = "Minutes", @class = "total-minutes" } ) %> </td> </tr> <% } %> </tbody> </table> <button type="submit">Save</button> <% } %> 处理程序并将值发送到服务器:

.submit

在此示例中,请注意我使用.on()方法而不是$(document).on('#myForm', 'submit', function () { var items = []; $('table tbody tr').each(function() { items.push({ totalHours: $(this).find('td input.total-hours').val(), totalMinutes: $(this).find('td input.total-minutes').val() }); }); var data = { employeeId: employeeId, // <!-- It's not very clear from your code where is this supposed to come from year: $('#year').val(), month: $('#month').val(), items: items }; $.ajax({ url: this.action, type: this.method, contentType: 'application/json', data: JSON.stringify(data), success: function (result) { // TODO: here you could handle the response from the server alert('Your request has been successfully processed.'); }, error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); } }); return false; }); 的方法,该方法已弃用且不应再使用。

答案 1 :(得分:1)

这个答案是针对你的第一个问题。

您可以使用form.serialize()发送所有表单数据。例如

$.ajax({
    ...
    data: $('#yourformId').serialize(),
    ...
});