使用 AJAX 、jquery、post.dataTables的剃刀页面未捕获类型错误:无法设置null的属性(设置“data”)

vh0rcniy  于 2022-11-03  发布在  jQuery
关注(0)|答案(1)|浏览(140)

这是我的剃刀页面,有一个DataTable,列和列中的一个href。当我点击_UsersSearchParams.cshtml中的搜索按钮时,Index.cshtml $("#frmUserSearch").submit(function (event)中触发了一个click事件。我试图使用 AJAX 调用函数loaddata(),但遇到了此错误。

_用户搜索参数.cshtml

@model UserIndexViewModel

@{
    string LabelClass = "col-sm-1";
    string InputClass = "col-sm-2";
}

<div class="row margin-bottom">
    <div class="col-sm-12">
        @using (Html.BeginForm("Index", "Users", FormMethod.Post, new { id = "frmUserSearch" }))
        {

        <div class="form-horizontal">
            <div class="form-group">

                <div class="@LabelClass">
                    @Html.LabelFor(m => m.User.Email, new { @class = "control-label" })
                </div>
            </div>
            <div class="form-group">
                <div class="@LabelClass">
                    @Html.LabelFor(m => m.User.FirstName, new { @class = "control-label" })
                </div>
                <div class="@InputClass form-input-max-md">
                    @Html.TextBoxFor(m => m.User.FirstName, new { @class = "form-control", tabindex = 2 })
                </div>
            </div>
            <div class="form-group" style="margin-top: 25px">
                <div class="col-sm-12" style="text-align: center">
                    <button id="btnSubmit" class="btn btn-primary" type="submit" tabindex="18">Search</button>
                    <button class="btn bg-navy" type="reset" id="clearForm" tabindex="19">Clear</button>
                </div>
            </div>
        </div>
        }
    </div>
</div>

用户/索引.cshtml

@model UserViewModel

<style>
    .modal-label-col {
        float: left;
        text-align: left !important;
        width: 170px;
        position: relative;
        min-height: 1px;
        padding-right: 5px;
        margin-left: 10px;
    }

    @@media only screen and (max-width: 965px) {
        #tblSearchData td:nth-of-type(1):before {
            content: "Active";
        }

        #tblSearchData td:nth-of-type(2):before {
            content: "User";
        }

        #tblSearchData td:nth-of-type(3):before {
            content: "Username";
        }

        #tblSearchData td:nth-of-type(4):before {
            content: "Website";
        }

        #tblSearchData td:nth-of-type(5):before {
            content: "Email";
        }

        #tblSearchData td:nth-of-type(6):before {
            content: "Date Added";
        }

        }
    }</style>

@section PageTitle{
    <h1 class="pagetitle">Users</h1>
}

    @await Html.PartialAsync("~/Views/Users/_UsersSearchParams.cshtml", Model)

    @await Html.PartialAsync("~/Views/Users/_UserContextMenu.cshtml")

    <div class="row error-content" style="margin-top: 10px; display: none;">
        <div class="col-sm-12">
            <div class="box box-danger">
                <div class="box-header bg-red-gradient">
                    <h4 class="col-sm-12">Error</h4>
                    <h4 class="col-sm-12">
                        <span class="error-text">An error occurred </span><a class="info-link text-black" style="font-size: smaller; padding-left: 20px;" href="#" onclick="toggleErrorDetails(this, event);">view details</a>
                    </h4>
                </div>
                <div class="box-body bg-red-gradient error-details" style="padding-left: 25px; display: none;">
                    <span id="lblError"></span>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-sm-12">
            <div class="box">
                <div class="box-header">
                    <h3 class="box-title">Search Results</h3>
                </div>
                <div class="box-body">
                    <table id="tblSearchData" class="table table-hover table-adaptive" cellspacing="0" width="100%">
                        <thead>
                            <tr>
                                <th>Active</th>
                                <th>FirstName</th>
                                <th>LastName</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>

        </div>
    </div>

    @section header{
    <link rel="stylesheet" href="~/css/bundles/dt.css" />
    <link rel="stylesheet" href="~/css/bundles/datetimepicker.css" />
}
    @section scripts{
    <script src="~/js/bundles/datetimepicker.js"></script>
    <script src="~/js/bundles/dataTables.js"></script>

    <script>
        var phoneRegex = /^\(?\d{3}\)?[- ]?\d{3}[- ]?\d{4}$/;
        var _selectedCustomerId = 0;

        $(document).ready(function () {
            $('input').removeClass('input-validation-error');
            $('select').removeClass('input-validation-error');

            $.fn.dataTable.moment('M/D/YYYY', 'en-US');

            $("#clearForm").click(function (event) {
                var form = $(this.closest("form"));
                form.find(':input').val('');
                event.preventDefault();
            });

            $(".datetimepicker").datetimepicker({
                format: 'L'
            });
        });

        function loaddata() {

            var table = $("#tblSearchData").DataTable({

                "processing": true, // for showing progress bar
                "serverSide": true, // for processing server side
                "filter": true, // this is for disabling filter (search box)
                "orderMulti": false, // for disabling multiple column at once
                "order": [[5, "desc"]], // default sort on date added descending
                "pageLength": 15,
                "lengthMenu": [5, 10, 15, 25, 50],
                "stateSave": true,
                "stateDuration": 0,
                "stateSaveParams": function (settings, data) {
                    data.start = 0;
                },
                "language": {
                    "emptyTable": "No users were found for specified search parameters"
                },

                ajax: {
                    url: "Users/LoadData",
                    "type": "POST",
                    "datatype": "json",
                    data: function (d) {
                        return {
                            ...d,
                            User: {
                                Phone: $('#User_Phone').val(),
                                Email: $('#User_Email').val(),
                                LastName: $('#User_LastName').val(),
                                FirstName: $('#User_FirstName').val(),

                            },

                            MembershipRoleId: $('#UserMembershipRoleId').val()
                        };
                    },
                },
                drawCallback: function (result) {
                    if (result && result.json && result.json.isError) {
                        $('.error-text').text(result.json.errorMessage);
                        const details = result.json.errorDetails.replace(/\r\n/g, '<br />').replace(/\r/g, '<br />');
                        $('#labelErrorDetails').html(details);

                        $('.error-content').insertBefore('#tblSearchData');
                        $('.error-content').show();
                    }
                },
                columnDefs: [
                    {
                        "targets": [0, 1],
                        "type": "html"
                    }
                ],

                columns: [

                    {
                        "data": "user", "name": "User", "autoWidth": true, "searchable": true, "orderable": true,
                        "render": function (data, type, row, meta) {
                            var link = '<a href="/Users/Info/' + row["id"] + '">' + data + '</a>';
                            return link;
                        }
                    },

                    { "data": "id", "name": "Id", "autoWidth": true, "searchable": false, "visible": false }
                ]
            });
        }

        $("#frmUserSearch").submit(function (event) {
            $('input').removeClass('input-validation-error');
            $('select').removeClass('input-validation-error');
            event.preventDefault();
            const validationFailures = getValidationFailures();
            if (validationFailures) {
                event.preventDefault();

                var errorMsg = validationFailures;
                showError('Invalid Input', errorMsg);

                return false;
            }

            $("#tblSearchData").DataTable().ajax.reload();
            //loaddata();
        });

        document.addEventListener('contextmenu', onContextMenu, false);

                // #endregion menu
    </script>
}
ecfsfe2w

ecfsfe2w1#

下面是一个关于使用ajax.reload()的工作演示:
HTML格式:

<button onclick="test()">RefreshData</button>
<table id="tblList" class="table table-striped table-bordered" style="width:100%">
    <thead>
        <tr>
            <th>a</th>
            <th>b</th>
            <th>c</th>
            <th>d</th>
        </tr>
    </thead>
</table>

js:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.css">
function test() {
            $('#tblList').DataTable().ajax.reload();
        }
        function loaddata() {
            var data = {};
            data.id = $("#id").val();
            $('#tblList').DataTable({
                destroy: true,
                ajax: {
                    "type": "POST",
                    "url": '/LoadData',
                    "dataType": "json",
                    "data": function(d) {
                        d.id = $("#id").val();
                    }

                },
                columns: [
                    { "data": "a", responsivePriority: 1, "searchable": true },
                    { "data": "b", responsivePriority: 2, "searchable": true },
                    { "data": "c", responsivePriority: 3, "searchable": true },
                    { "data": "d", responsivePriority: 4, "searchable": true },
                ],
            });

        };
$(function() {
            loaddata();
        })

处理措施:

[HttpPost]
        [Route("LoadData")]
        public IActionResult GetFinanceiro(SearchModel s)
        {
            List<DataTableModel> l = new List<DataTableModel> {
            new DataTableModel{  a="a1"+s.Id,b="b1"+s.Id,c="c1"+s.Id,d="d1"+s.Id},
            new DataTableModel{  a="a2",b="b2",c="c2",d="d2"},
            new DataTableModel{  a="a3",b="b3",c="c3",d="d3"},
            new DataTableModel{  a="a4",b="b4",c="c4",d="d4"},

            };
            return Json(new { data = l });
        }

型号:

public class DataTableModel
    {
        public string a { get; set; }
        public string b { get; set; }

        public string c { get; set; }

        public string d { get; set; }

    }
    public class SearchModel 
    {
        public int Id { get; set; }
    }

结果:

相关问题