Home > OS >  razor pages with ajax, jquery, post. dataTables Uncaught TypeError: Cannot set properties of null (s
razor pages with ajax, jquery, post. dataTables Uncaught TypeError: Cannot set properties of null (s

Time:10-28

This is my razor page with a DataTable, Columns and a href within the column. When I click on the search button within _UsersSearchParams.cshtml, a click event is fired within Index.cshtml $("#frmUserSearch").submit(function (event). I am trying to make a ajax call function loaddata() but getting this error.

enter image description here

_UsersSearchParams.cshtml

@model UserIndexViewModel

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


<div >
    <div >
        @using (Html.BeginForm("Index", "Users", FormMethod.Post, new { id = "frmUserSearch" }))
        {

        <div >
            <div >
                
                <div >
                    @Html.LabelFor(m => m.User.Email, new { @class = "control-label" })
                </div>
            </div>
            <div >
                <div >
                    @Html.LabelFor(m => m.User.FirstName, new { @class = "control-label" })
                </div>
                <div >
                    @Html.TextBoxFor(m => m.User.FirstName, new { @class = "form-control", tabindex = 2 })
                </div>
            </div>
            <div  style="margin-top: 25px">
                <div  style="text-align: center">
                    <button id="btnSubmit"  type="submit" tabindex="18">Search</button>
                    <button  type="reset" id="clearForm" tabindex="19">Clear</button>
                </div>
            </div>
        </div>
        }
    </div>
</div>

Users/Index.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 >Users</h1>
}

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

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


    <div  style="margin-top: 10px; display: none;">
        <div >
            <div >
                <div >
                    <h4 >Error</h4>
                    <h4 >
                        <span >An error occurred </span><a  style="font-size: smaller; padding-left: 20px;" href="#" onclick="toggleErrorDetails(this, event);">view details</a>
                    </h4>
                </div>
                <div  style="padding-left: 25px; display: none;">
                    <span id="lblError"></span>
                </div>
            </div>
        </div>
    </div>


    <div >
        <div >
            <div >
                <div >
                    <h3 >Search Results</h3>
                </div>
                <div >
                    <table id="tblSearchData"  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>
}

CodePudding user response:

Here is a working demo about using ajax.reload():

html:

<button onclick="test()">RefreshData</button>
<table id="tblList"  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();
        })

action:

[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 });
        }

Models:

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; }
    }

result: enter image description here

  • Related