c# - 将 Jquery 数据表中的所有数据从 View 绑定(bind)到 Controller

标签 c# jquery asp.net-mvc datatables

我将 View 中的数据绑定(bind)到 Controller,因此稍后我可以对数据做我想做的事。在我的 View 中,我使用 dataTable@Html.EditorForModel() 来呈现我的 View 。

查看

<form action="xx" method="POST">
<table id="myTable" class="table table-bordered table-hover table-striped">
    <thead>
        <tr>
            <th></th>
            <th>
                @Html.DisplayNameFor(model => model.Field1)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Field2)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Field3)
            </th>
        </tr>
    </thead>
    <tbody>
    @if (Model != null)
    {
        @Html.EditorForModel()
    }
    </tbody>
    <tfoot></tfoot>
</table>

<input type="submit" value="submit" />
</form>

脚本

$("#myTable").dataTable({
        searching: false,
        ordering: false,
        responsive: true,
        "bLengthChange" : false,
        "pageLength": 20,
        "bStateSave": true
    });

Controller

[HttpPost]
public ActionResult MyAction(List<MyModel> MyListModel)

如果 dataTables 中的数据不超过 1 页,则此方法效果很好。如果它超过一页,那么我的 Controller 要么只能接收第一页的列表数据,要么什么都不接收(null)

我应该如何将 DataTables 中的所有数据从 View 绑定(bind)到 Controller ?此绑定(bind)应包括所有页面,而不仅仅是第一个页面

最佳答案

我不确定你是如何触发数据更新的,所以假设它是一个按钮,下面应该起作用:

$('#your-button').on('click', function(e){
   var data = ('#myTable').DataTable().$('input,select,textarea').serialize();

   $.ajax({
      url: '/MyController/MyAction/',
      data: data,
      success: function(){
         alert('success');
      }, 
      error: function(){
         alert('failure');
      }
   });
});

编辑 1:

根据 this回答How to post data for the whole table using jQuery DataTables ,如果您打算使用表单,请使用以下内容:

var table = $('#myTable').DataTable();

$('#myForm').on('submit', function(e){
   var form = this;

   var params = table.$('input,select,textarea').serializeArray();

   $.each(params, function(){
      if(!$.contains(document, form[this.name])){
         $(form).append(
            $('<input>')
               .attr('type', 'hidden')
               .attr('name', this.name)
               .val(this.value)
         );
      }
   });
});

关于c# - 将 Jquery 数据表中的所有数据从 View 绑定(bind)到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44108199/

相关文章:

c# - 如何绘制图像?

c# - 当控制台输出重定向到文本框时发生跨线程操作

javascript - "loading gif"背景图像问题 (IE/Edge)

javascript - JQuery .post() 不返回数据

jquery css 位置固定

c# - GridView SelectedValue 通过 Select 上的 LinkBut​​ton

c# - 事件集锦

c# - 将数据数组从 Javascript 传递到 C#

asp.net-mvc - 什么是浏览器缓存?它从网页数据中存储什么?

jquery - 如何在 asp.net mvc 中通过 jquery ajax 删除行后更新列表?