c# - 将 Ajax 数组发送到 Controller

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

enter image description here

enter image description here

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

因此,我需要将这些数据作为数组 ajax post 发送到 MVC Controller ,然后在 Controller 内选择这些内容。当我单击保存按钮时,应该会发生这种情况

我的发布方法如下(没有上面的数组详细信息):

 $("#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;
       });

我的 Controller 如下(没有 jquery 数组映射):

[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. 如何在 Controller 内操作该数组?

最佳答案

您可以首先在服务器上定义一个 View 模型来表示您想要检索的数据:

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; }
}

然后让您的 Controller 操作将此 View 模型作为参数:

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

下一步是稍微修复你的 View ,因为现在你似乎正在对输入字段进行硬编码,而不是使用 html 帮助器并为输入字段定义错误的 id 和名称(在 HTML 中,idname 属性不能以数字开头)。

以下是生成表格的方法:

<% 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>
<% } %>

最后,您可以拥有一些 javascript 文件,该文件将订阅表单的 .submit 处理程序并将值发送到服务器:

$(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;
});

在此示例中,请注意我如何使用 .on()方法而不是 .live() ,后者已被弃用,不应再使用。

关于c# - 将 Ajax 数组发送到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15447199/

相关文章:

c# - 什么是NullReferenceException,如何解决?

c# - 使用构造函数或图形缩放位图的结果?

.net - 为什么通过菜单项的单击事件打开的模态对话框会处理所有窗口消息?

当 WCF 方法抛出异常时,jQuery 成功回调以空响应调用

JQuery DatePicker 约束输入 : true not working like I think it should

c# - ObservableCollection 的网格 ObservableCollection 的网格

c# - 如何在调用 httpcontext.current 的 mvc Controller 上进行集成测试

c# - Visual Studio 201 7's "Implement Interface”命令可以生成 C# 5 代码吗?

C#:将单个自定义类数据绑定(bind)到表单控件(复选框?)

javascript - 拖动以像在 iPhone 中一样使用 jQuery 更改图像幻灯片