Jquery数据表绑定来自ajax的数据

时间:2017-04-27 15:14:57

标签: c# jquery ajax asp.net-mvc datatable

我对如何从控制器绑定数据有疑问。 这是个主意: 我有数据表中的数据列表。我需要从datatable中删除1个数据。我使用ajax post在控制器中调用actionresult并发送模型。我的控制器将删除数据,并返回模型进行查看。

这是我的viewmodels:

public class SampleHeaderViewModels
{
    [Display(Name = "ID")]
    public int intID { get; set; }

    [Display(Name = "Field 1")]
    public string txtField1 { get; set; }

    [Display(Name = "Field 2")]
    public string txtField2 { get; set; }
}

public class SampleDetailViewModels
{
    [Display(Name = "ID")]
    public int intID { get; set; }

    [Display(Name = "Line")]
    public int intLine { get; set; }

    [Display(Name = "Detail 1")]
    public string txtDetail1 { get; set; }

    [Display(Name = "Detail 2")]
    public string txtDetail2 { get; set; }
}

public class SampleViewModels
{
    public SampleHeaderViewModels Header { get; set; }
    public List<SampleDetailViewModels> Detail { get; set; }

    public SampleViewModels()
    {
        Header = new SampleHeaderViewModels();
        Detail = new List<SampleDetailViewModels>();
    }
}

这是我的观点:

<div class="row">
    <div class="block">
        <div class="block-content controls">
            <div class="col-md-6">
                <div class="row-form">
                    <div class="col-md-4">
                        @Html.LabelFor(m => m.Header.txtField1, htmlAttributes: new { @class = "control-label" })
                    </div>
                    <div class="col-md-8">
                        @Html.HiddenFor(m => m.Header.intID)
                        @Html.TextBoxFor(m => m.Header.txtField1, htmlAttributes: new { @class = "form-control" })
                    </div>
                </div>
                <div class="row-form">
                    <div class="col-md-4">
                        @Html.LabelFor(m => m.Header.txtField2, htmlAttributes: new { @class = "control-label" })
                    </div>
                    <div class="col-md-8">
                        @Html.TextBoxFor(m => m.Header.txtField2, htmlAttributes: new { @class = "form-control" })
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="row">
    <div class="block">
        <div class="block-content controls">
            <div class="col-md-12">
                <div class="row-form">
                    <table id="tbDataTable" class="table table-bordered">
                        <thead>
                            <tr>
                                <td>

                                </td>
                                <td>
                                    @Html.LabelFor(m => m.Detail.FirstOrDefault().intLine)
                                </td>
                                <td>
                                    @Html.LabelFor(m => m.Detail.FirstOrDefault().txtDetail1)
                                </td>
                                <td>
                                    @Html.LabelFor(m => m.Detail.FirstOrDefault().txtDetail2)
                                </td>
                            </tr>
                        </thead>
                        <tbody>
                            @if (Model.Detail != null)
                            {
                                for (int x = 0; x <= Model.Detail.Count - 1; x++)
                                {
                                    <tr>
                                        <td>
                                            <button type="button" class="btn btn-primary" onclick="return DeleteDetail('@Model.Detail[x].intLine');">Delete</button>
                                        </td>
                                        <td>
                                            @Html.DisplayFor(m => @Model.Detail[x].intLine)
                                            @Html.HiddenFor(m => @Model.Detail[x].intLine)
                                        </td>
                                        <td>
                                            @Html.DisplayFor(m => @Model.Detail[x].txtDetail1)
                                            @Html.HiddenFor(m => @Model.Detail[x].txtDetail1)
                                        </td>
                                        <td>
                                            @Html.DisplayFor(m => @Model.Detail[x].txtDetail2)
                                            @Html.HiddenFor(m => @Model.Detail[x].txtDetail2)
                                        </td>
                                    </tr>
                                }
                            }
                    </table>
                </div>
                <div class="row-form">
                    <div class="col-md-2">
                        <button type="button" id="btnAddDetail" class="btn btn-info">Add Detail</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

这是我的Javascript:

&#13;
&#13;
function DeleteDetail(intLine)
    {
        debugger;
        
        var modelHeader = {
            "intID": $('#@Html.IdFor(m => m.Header.intID)').val(),
            "txtField1": $('#@Html.IdFor(m => m.Header.txtField1)').val(),
            "txtField2": $('#@Html.IdFor(m => m.Header.txtField2)').val(),
        };

        var modelDetail = @Html.Raw(JsonConvert.SerializeObject(Model.Detail));

        $.ajax({
            url: '/Sample/DeleteDetail',
            type: 'POST',
            datatype: 'JSON',
            contentType: 'application/json',
            data: JSON.stringify(
                {
                    objHeader : modelHeader,
                    objDetail : modelDetail,
                    intLine : intLine
                }),
            cache: false,
            success: function (data) {
                @*window.location.replace('@Url.Action("Detail")');*@
                },
            error: function (data) {
                console.log(data);
            }
        });
    }
&#13;
&#13;
&#13;

这是我的控制者:

[HttpPost]
    public ActionResult DeleteDetail(SampleHeaderViewModels objHeader, List<SampleDetailViewModels> objDetail, int intLine)
    {
        objDetail.Remove(objDetail.Where(m => m.intLine == intLine).FirstOrDefault());

        SampleViewModels obj = new SampleViewModels();
        obj.Header = objHeader;
        obj.Detail = objDetail;

        TempData["model"] = obj;

        return View("Index", obj);
    }

问题是: 在我的代码中,当我按下&#34;删除&#34;在datatable中的按钮,它将在javascript中调用函数AJAX POST DeleteDetail。它会将Header模型和Detail模型发送给我的Controller。我的控制器将删除所选行并将模型返回到View。而我的View获得了最新型号。哪一行已被删除。 但它不会渲染数据表。所以删除的数据仍然存在。 当AJAX成功时,我尝试使用@url发布页面,但仍然没有运气。 如何强制数据表绑定最新模型?

感谢。

编辑:

我尝试刷新数据而不刷新页面。只需刷新数据表。

这是我的控制器:

public ActionResult DeleteDetail(SampleHeaderViewModels objHeader, List<SampleDetailViewModels> objDetail, int intLine)
    {
        objDetail.Remove(objDetail.Where(m => m.intLine == intLine).FirstOrDefault());

        SampleViewModels obj = new SampleViewModels();
        obj.Header = objHeader;
        obj.Detail = objDetail;

        TempData["model"] = obj;

        var json = JsonConvert.SerializeObject( new {detail = obj.Detail});

        return Content(json, "application/json");
    }

这是我的Javascript:

&#13;
&#13;
function DeleteDetail(intLine)
    {
        debugger;
        var modelHeader = {
            "intID": $('#@Html.IdFor(m => m.Header.intID)').val(),
            "txtField1": $('#@Html.IdFor(m => m.Header.txtField1)').val(),
            "txtField2": $('#@Html.IdFor(m => m.Header.txtField2)').val(),
        };

        var modelDetail = @Html.Raw(JsonConvert.SerializeObject(Model.Detail));

        $.ajax({
            url: '/Sample/DeleteDetail',
            type: 'POST',
            datatype: 'JSON',
            contentType: 'application/json',
            data: JSON.stringify(
                {
                    objHeader : modelHeader,
                    objDetail : modelDetail,
                    intLine : intLine
                }),
            cache: false,
            success: function (data) {
                debugger;

                table = $("#tbDataTable").dataTable();
                oSettings = table.fnSettings();

                table.fnClearTable(this);

                for (var i=0; i < data.detail.length; i++)
                {
                    table.oApi._fnAddData(oSettings, data.detail[i]);
                    //this part always send error DataTables warning: table id=tbDataTable - Requested unknown parameter '0' for row 0.
                }

                oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
                table.fnDraw();

                },
            error: function (data) {
                console.log(data);
            }
        });
    }
&#13;
&#13;
&#13;

但是它向我发送了一个错误DataTables警告:table id = tbDataTable - 请求的未知参数&#39; 0&#39;第0行 视图和视图模型仍然像第一个问题一样。 请帮我。

3 个答案:

答案 0 :(得分:1)

如果您从数据库中成功删除了一条记录,则Action方法返回true,其他方式返回false:

Option Explicit

Public Function GOOGLE_COUNT(searchTerm As String, xRes As Long, yRes As Long, Optional timeout As Long = 10) As Long

    Dim url As String
    Dim objIE As Object
    Dim currPage As Object
    Dim stTimer As Double, tElapsed As Single
    Dim valueResult As Object

    'create URL to page with these image criteria
    url = "https://www.google.com/search?q=" & searchTerm & _
                        "&tbm=isch&source=lnt&tbs=isz:ex,iszw:" & xRes & ",iszh:" & yRes

    'initiating a new instance of Internet Explorer and asigning it to objIE
    Set objIE = CreateObject("InternetExplorer.Application")

    'Google images search
    objIE.navigate url
    Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop
    Set currPage = objIE.document
    Dim myDiv As Object: Set myDiv = currPage.getElementById("fbar")
    Dim elemRect As Object: Set elemRect = CallByName(myDiv, "getBoundingClientRect", VbMethod)
    stTimer = Timer
    'Scroll until bottom of page is in view
    Do Until elemRect.bottom > 0 Or tElapsed > timeout 'timeout after n seconds
        currPage.parentWindow.scrollBy 0, 10000
        Set elemRect = CallByName(myDiv, "getBoundingClientRect", VbMethod)
        tElapsed = Timer - stTimer
    Loop
    myDiv.ScrollIntoView
    'Count the images
    Set valueResult = currPage.getElementById("rg_s").getElementsByTagName("IMG")
    GOOGLE_COUNT = valueResult.Length
    objIE.Quit

End Function

Sub foo()

MsgBox GOOGLE_COUNT("St. Mary", 1366, 768)

End Sub

在ajax的成功方法中重新加载当前页面,

 public ActionResult DeleteDetail(SampleHeaderViewModels objHeader, 
  List<SampleDetailViewModels> objDetail, int intLine)
  {
     ...
  ...
  db.SaveChanges();
  return Json(new { Success = true; });
  }

答案 1 :(得分:0)

jQuery:

                                  

<script>
    var Display;

    $(document).ready(function () {

        $('#ProductTable').DataTable();

        Display = function () {
            var URL = '@Url.Action("GetProductsData", "Product")';

            oTable = $('#ProductTable').DataTable({
                dom: 'Bfrtip',
                "bPaginate": false,
                buttons: [
                    'excel', 'pdf', 'print'
                ],
                "processing": false,
                "serverSide": false,
                "bSort": false,
                "searching": true,
                "sAjaxSource": URL,
                "pageLength": 10,
                "bDestroy": true,
                "bLengthChange": true,
                "scrollX": true,
                "scrollY": ($(window).height() - 200),
                "pagingType": "full_numbers",
                "sEmptyTable": "Loading data from server",
                "fnServerData": function (sSource, aoData, fnCallback) {

                    $.ajax({
                        "dataType": 'json',
                        "type": "POST",
                        "url": sSource,
                        "data": aoData,
                        "success": fnCallback
                    });
                },
                "columns": [
                                  {

                                      "sWidth": "5%",
                                      "bSortable": true,
                                      "sClass": "TextCenter ID",
                                      "visible": false,
                                      "render": function (data, type, row, meta) {
                                          return (row[0])
                                      }
                                  },
                                  {

                                      "sWidth": "5%",
                                      "sClass": "rightalign ",
                                      "render": function (data, type, row, meta) {
                                          return (row[1])
                                      }
                                  },
                                   {

                                       "sWidth": "10%",
                                       "sClass": "rightalign TA_C",
                                       "render": function (data, type, row, meta) {
                                           return (row[2])
                                       }
                                   },

                                  {
                                      "swidth": "5%",
                                      "sclass": "TextCenter Action",
                                      "render": function (data, type, row, meta) {
                                          return '<button class="btn btn-primary fa fa-check-square"  title="Edit" onclick="editdata(' + row[0] + ',\'' + row[1] + '\',' + row[2] + ')"></button>' +
                                      '<button class="btn btn-danger glyphicon glyphicon-trash" title="Delete"  onclick="deletedata(' + row[0] + ')" style="margin-left: 10px;"></button>';

                                          }
                                  }


                ], "fnInitComplete": function (oSetting, json) {

                }
            });
        }



        Display();

        $("#btninsert").click(function () {


            var fdata = new FormData();

            fdata.append("id","0");
            fdata.append("pname",$("#txtpname").val());
            fdata.append("pprice", $("#txtpprice").val());


            $.ajax({
                url: '@Url.Action("InupProduct", "Product")',
                type: "POST",
                contentType: false, // Not to set any content header
                processData: false, // Not to process data
                data: fdata,
                success: function (result) {
                    if (result == 1) {

                        swal("Successfully Product Inserted!", "", "success", {
                            button: "Close",
                        });

                        clear();
                        Display();
                    }
                    else {

                        swal("Product Not Inserted!", "", "error", {
                            button: "Close",
                        });
                    }

                },
                error: function (err) {
                    alert(err.statusText);
                }
            });

        });


        $("#btnupdate").click(function () {
            var fdata = new FormData();

            fdata.append("id", $("#hdnID").val());
            fdata.append("pname", $("#txtuppname").val());
            fdata.append("pprice", $("#txtuppprice").val());


            $.ajax({
                url: '@Url.Action("InupProduct", "Product")',
                type: "POST",
                contentType: false, // Not to set any content header
                processData: false, // Not to process data
                data: fdata,
                success: function (result) {
                    if (result == 1) {

                        swal("Successfully Product Updated!", "", "success", {
                            button: "Close",
                        });
                        clear();
                        Display();
                        $('#mmd').modal('hide');

                    }
                    else {
                        swal("Product Not Updated!", "", "error", {
                            button: "Close",
                        });
                    }

                },
                error: function (err) {
                    alert(err.statusText);
                }
            });
        });

        function clear() {
            $("#txtpname").val("");
            $("#txtpprice").val("");
        }
    });

    function deletedata(ID) {
        bootbox.confirm({
            title: "Please Confirm",
            message: "Are you sure to delete this record.",
            buttons: {
                cancel: {
                    label: '<i class="fa fa-times"></i> Cancel'
                },
                confirm: {
                    label: '<i class="fa fa-check"></i> Confirm'
                }
            },
            callback: function (result) {
                if (result == true) {
                    var data = { "ID": ID };
                    $.ajax({
                        url: '@Url.Action("deleteRecord", "Product")',
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        data: JSON.stringify(data),
                        dataType: "json",
                        success: function (response) {

                            if (response == 1) {
                                swal("Successfully Product Deleted!", "", "success", {
                                    button: "Close",
                                });

                                    Display();


                            }
                            else {
                                swal("Product Not Deleted!", "", "error", {
                                    button: "Close",
                                });

                            }
                        }
                    });
                }
            }
        });
    }

    function editdata(pid,pname,price)
    {

        $("#hdnID").val(pid);
        $("#txtuppprice").val(price);
        $("#txtuppname").val(pname);
        $('#mmd').modal();          
    }
</script>

<style>
    .dataTables_scrollBody{
            position: relative;
overflow: auto;
margin-top: -5%;
width: 100%;
height: 502px;
    }
</style>

答案 2 :(得分:0)

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js"></script>
<script src="https://unpkg.com/sweetalert@2.1.0/dist/sweetalert.min.js"></script>