weixin_33701251 2015-12-22 15:43 采纳率: 0%
浏览 36

MVC5 jQuery阿贾克斯

I want to select multiple rows and then click on a button to approve/deny those rows. I have successfully updated the rows I want to approve in db. But when ajax callback, I ran table.draw() and it doesn't show the saved result. I don't know how to take the saved result and refresh back to the DataTable.

Also I am new to MVC and jQuery, I was fumbling around to make it barely work. Could you help point out what do I need to improve/fix to make this work better?

Here are my codes:

View (table part):

<table id="myDataTable" class="display">
            <thead>
                <tr>
                    <th>Clearance Name</th>
                    <th>Approved</th>
                    <th>Approver</th>
                    <th>DateTime</th>
                    <th>Deny Reason</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model.Request.RequestClearances)
                {
                    <tr id="@item.RequestClearanceID">
                        <td>@item.Clearance.ClearanceName</td>
                        <td>@item.IsApproved</td>
                        <td>@item.ApprovedUser</td>
                        <td>@item.ModifiedDate</td>
                        <td>@item.DenialReason</td>
                    </tr>
                }
            </tbody>
</table>
<div><input type="button" id="btnApprove" value="Approve" /><input type="button" id="btnDeny" value="Deny" /></div>

View (jQuery part):

<script>
    $(function () {
        var table = $("#myDataTable").DataTable();

        $("#myDataTable tbody").on('click', 'tr', function () {
            var tr = $(this).closest("tr");
            var rowText = tr.children("td").text();

            if (! rowText.match("True") ) {
                $(this).toggleClass('selected');
            }

        });

        $("#btnApprove").click(function () {
            var idArray = $.map(table.rows('.selected').ids(), function (item) {
                return item;
            });

            $.ajax({
                type: "POST",
                url: '@Url.Action("UpdateApproveDeny")',
                cache: false,
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                data: JSON.stringify({ requestClearanceIDs: idArray, isApproved: "true" }),
                success: function () {
                    table.draw();
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $("#message").text(JSON.stringify(jqXHR).toString());
                    alert("AJAX error: " + textStatus + ' : ' + errorThrown);
                }
            });
        });
    });
</script>

Control:

public JsonResult UpdateApproveDeny(string[] requestClearanceIDs, string isApproved)
        {
            if (requestClearanceIDs == null) return Json("fail",JsonRequestBehavior.AllowGet);
            int? requestID = 0;
            foreach (var requestClearanceID in requestClearanceIDs)
            {
                int id = 0;
                Int32.TryParse(requestClearanceID, out id);              
                requestID = rc.RequestID;
                rc.IsApproved = Convert.ToBoolean(isApproved);
                rc.ModifiedBy = User.Identity.Name;
                rc.ModifiedDate = DateTime.Now;
                rc.ApprovedUser = User.Identity.Name;
                db.SaveChanges();
            }

            return Json("success",JsonRequestBehavior.AllowGet);
        }
  • 写回答

1条回答 默认 最新

  • weixin_33735676 2015-12-24 19:54
    关注

    Since you're using DataTables in a static fashion you'll need to replace your table content in the AJAX callback then rebind $("#myDataTable").DataTable() because the original table will be replaced.

    Add a partial view

    Adjust your main view to fill your table with a partial view.

    <div id="tableData">
        @Html.Partial("_ClearancesTable", Model.Request.RequestClearances)
    </div>
    <div>
        <input type="button" id="btnApprove" value="Approve" />
        <input type="button" id="btnDeny" value="Deny" />
    </div>
    

    _ClearancesTable.cshtml

    @model IEnumerable<RequestClearances>
    
    <table id="myDataTable" class="display">
        @foreach (var item in Model)
        {
            ...
        }
    </table>
    

    You can either make a second AJAX call to retrieve new table data or alter your first response to return the new data.

    Replace the JSON result to take advantage of the partial view and to reduce this to one server call.

    public ActionResult UpdateApproveDeny(string[] requestClearanceIDs, string isApproved)
    {
        ...
        db.SaveChanges();
        var clearances = db.GetClarances();
        return PartialView("_ClearancesTable", clearances);
    }
    

    Replace and Rebind

     success: function(partialResult) {
         $("#tableData").html(partialResult)
         $("#myDataTable").DataTable();
     }
    
    评论

报告相同问题?