使用ajax更新DataTable内容

时间:2017-08-20 07:34:42

标签: jquery json ajax asp.net-mvc datatable

我正在使用AJAX处理DataTables,我在页面加载时生成一个表。我的代码的第一部分工作正常。然后我有一个下拉菜单,用于过滤DataTable中的用户。我可以选择用户名并向控制器发送POST请求,它会生成json数据。但我无法找到如何发送此json数据并更新DataTable的方法。这是我的代码:

public ActionResult IndividualUser()
{            
    var taskAnswer = new List<TaskAnswerView>();
    return View(taskAnswer);
}

public ActionResult IndividualUserGetData(string id)
{
    var now = DateTime.Now;
    var applicationUser = db.Users.FirstOrDefault(x => x.UserName == id);
    if (applicationUser != null)
    {
        var userId = applicationUser.Id;
        var user = db.Users.Find(userId);
        var list = db.TasksModels
            .Join(db.TaskToUsers, t => t.TasksModelID, usr => usr.TasksModelID, (t, usr) => new { t, usr })
            .Where(t1 => t1.usr.UserIdInt == user.ApplicationUserId)
            .Select(t1 => new
            {
                t1.t.Heading,
                t1.t.TasksModelID,
                t1.t.EndDate,
                t1.t.StartDate,
                t1.t.Content,
                t1.t.CreatedBy,
                t1.t.CreatedOn,
                Status = t1.t.EndDate > now && t1.t.StartDate < now ? "Open" : "Closed",

                ttu = t1.t.TaskToUsers.Select(t => new
                {
                    reply = t.ReplyToTasks.Where(x => x.TaskToUser.UserIdInt == user.ApplicationUserId).Select(r => new
                    {
                        answer = r.UserAnswer,
                        answerTime = r.AnswerTime,
                    }),
                    user = db.Users.Where(f => f.ApplicationUserId == user.ApplicationUserId).Select(u => new
                    {
                        fullName = u.Name + " " + u.Surname
                    })
                })
            }).ToList();
        return Json(new { data = list }, JsonRequestBehavior.AllowGet);
    }
    else
    {
        var data = db.TasksModels.Select(s => new
        {
            s.Heading,
            s.StartDate,
            s.EndDate,
            s.CreatedBy,
            s.CreatedOn,
            Status = s.EndDate > now && s.StartDate < now ? "Open" : "Closed",

            ttu = s.TaskToUsers.Select(t => new
            {
                reply = t.ReplyToTasks.Select(r => new
                {
                    answer = r.UserAnswer,
                    answerTime = r.AnswerTime,
                }),
                user = db.Users.Where(f => f.ApplicationUserId == t.UserIdInt).Select(u => new
                {
                    fullName = u.Name + " " + u.Surname
                })
            })
        }).ToList();

        return Json(new { data = data }, JsonRequestBehavior.AllowGet);
    }            
}
@model IEnumerable<DeadLiner.Models.TaskAnswerView>
@{
   ViewBag.Title = "Individual User";

   var options = new AjaxOptions()
    {        
      Url = Url.Action("IndividualUserGetData"),
      LoadingElementId = "loadingIndicator",        
    };
  }
@using (Ajax.BeginForm(options))
{
  <div class="tablecontainer">
    <p>
        @Html.DropDownList("id", new SelectList(new[] { "Ragim-A", "qurban" 
         }, "Murad"))
        <input type="submit" value="Submit" />
    </p>
    <div id="loadingIndicator" style="display:none;">Loading...</div>
    <table class="table table-bordered ui" id="myTable">
        <thead>
            <tr>
                <th>
                    Details
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Heading)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.StartDate)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.EndDate)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.CreatedBy)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.CreatedOn)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Status)
                </th>
            </tr>
        </thead>
    </table>
</div>
}

@section scripts
{
<script>
    $(document).ready(function () {
        $.fn.dataTable.moment('DD/MM/YYYY');
        $.fn.dataTable.moment('dddd, DD/MM/YYYY');

        var oTable = $("#myTable").DataTable({
            responsive: true,
            "ajax": {
                "url": "/TasksModels/IndividualUserGetData",
                "type": "get",
                "datatype": "json"
            },
            "columnDefs": [
                { "className": "dt-center", "targets": 6 }
            ],
            "order": [[3]],
            "columns": [
                {
                    "class": "details-control",
                    "orderable": false,
                    "data": null,
                    "defaultContent": ""
                },
                { "data": "Heading", "autoWidth": true },
                {
                    "data": "StartDate",
                    "autoWidth": true,
                    "render": function (data, type, row) {
                        if (type === 'display' || type === 'filter') {
                            var rowvalueallday = row["EndDate"];
                            if (rowvalueallday == 0) {
                                return (moment(data).format("ddd DD/MM/YYYY"));
                            } else {
                                return (moment(data).format("MMMM Do YYYY, HH:mm"));
                            }
                        }
                        return data;
                    }
                },
                {
                    "data": "EndDate",
                    "autoWidth": true,
                    "render": function (data, type, row) {
                        if (type === 'display' || type === 'filter') {
                            var rowvalueallday = row["EndDate"];
                            if (rowvalueallday == 0) {
                                return (moment(data).format("ddd DD/MM/YYYY"));
                            } else {
                                return (moment(data).format("MMMM Do YYYY, HH:mm"));
                            }
                        }
                        return data;
                    }
                },
                { "data": "CreatedBy", "autoWidth": true },
                {
                    "data": "CreatedOn",
                    "autoWidth": true,
                    "render": function (data, type, row) {
                        if (type === 'display' || type === 'filter') {
                            var rowvalueallday = row["EndDate"];
                            if (rowvalueallday == 0) {
                                return (moment(data).format("ddd DD/MM/YYYY"));
                            } else {
                                return (moment(data).format("MMMM Do YYYY, HH:mm"));
                            }
                        }
                        return data;
                    }
                },
                {
                    "data": "Status",
                    "autoWidth": true,
                    "render": function (data) {
                        if (data == "Open") {
                            return '<i class="fa fa-unlock bat" aria-hidden="true" style="color:green;"></i>';
                        }
                        return '<i class="fa fa-lock bat" aria-hidden="true" style="color:red;"></i>';
                    }
                }
            ]
        });

1 个答案:

答案 0 :(得分:0)

创建一个js函数,其中放置您的数据表代码,它的参数是您要应用于数据表的过滤器值。最初这些过滤器值为android.os.Debug.waitForDebugger(); null,当应用这些过滤器时,它们中包含一些值。将这些过滤器值与对这些服务器的数据表调用一起发布。在页面加载以及应用的过滤器上调用此函数。

在服务器上检查这些过滤器是否为空,然后在查询中应用它们,否则跳过它们。通过这种方式,您的功能将自己处理每一种可能性。