简体   繁体   中英

Reload DataTable on Every Page Refresh

All I am trying to do is that I want to refresh my DataTable when the page is relaoded/refreshed. Right now on refreshing the page it retains its data. My application is using ASP.Net MVC tech. Here is my Data Table and relevant functions:

$(document).ready(function () {


    //debugger;
    var table = $('#user_session_center_grid').DataTable({
        "searching": false,
        "colReorder": true,
        "lengthChange": false,
        "processing": true,
        "serverSide": true,
        "autoWidth": false,
        "ajax": {
            cache: false,
            url: "@Url.Action("GetUserSessionHistory", "LoggedIn")",
            type: 'POST',
            data: function (data) {
                data.SortBy = 'Month';
                data.FromDate = "";
                data.ToDate = "";
                data.userSearch = $('#userSearch').val();
                if (event) {
                    var objDtFilter = event.target;
                    if ($(objDtFilter).hasClass('dtFilter')) {
                        data.FromDate = event.target.getAttribute('fromdt');
                        data.ToDate = event.target.getAttribute('todt');
                    }
                    if ($(objDtFilter).hasClass('dtSort'))
                        data.SortBy = event.target.getAttribute('sort');
                    if ($(objDtFilter).hasClass('UserTypeFilter'))
                        data.value1 = event.target.getAttribute('value');
                    console.log(data.value1);
                }
            },
        },
        "language": {
            oPaginate: {
                sNext: '<i class="fa fa-chevron-right"></i>',
                sPrevious: '<i class="fa fa-chevron-left"></i>',
                sFirst: '<i class="fa fa-chevron-right"></i>',
                sLast: '<i class="fa fa fa-chevron-left"></i>'
            }
        },
        "columns": [
            {
                data: null,
                class: "userName",
                render: function (data, type, row) {
                    return "<div>" + data.FirstName + " " + data.LastName + "</div></td>";
                }
            },

            {
                data: null,
                class: "startDate",
                render: function (data, type, row) {
                    var parsedDate = JSON.parse(JSON.stringify(data.StartTime), ToJavaScriptDate);
                    return "<div>" + parsedDate + "</div></td>";
                }
            },

                //{ 'data': 'User_ID' },
                //{ 'data': 'FirstName' },
                //{ 'data': 'LastName' },
                //{ 'data': 'StartTime' },
        ],
    });

   table.on('draw', function () {
       var widthofPagination = $('.dataTables_paginate.paging_simple_numbers').width() + 25;
       $('#user_session_center_grid_info').css({ width: 'calc(100% - ' + widthofPagination + 'px)' });

   });
    $("#date_filter_ul.dropdown-menu li a").click(function () {
        //debugger;
        $('#date_filter_ul').removeClass('show');
        $(this).closest('#CategoryFilter').find('.csp-select > span').text("Duration:" + $(this).text());
        $('#user_session_center_grid').DataTable().ajax.reload();
    });

    $("#user_session_center_status_ul.dropdown-menu li a").click(function () {
        $('#user_session_center_status_ul').removeClass('open');
        $(this).closest('#StatusFilter').find('.csp-select > span').text($(this).text());
        $('#user_session_center_grid').DataTable().ajax.reload();
    });
});

Here are my controller functions:

public ActionResult UserSessionCenter()
    {
            if (Session["selectedCustomer"] == null)
            {
                Session["selectedCustomer"] = 9;
            }

            int customerId = (int)Session["selectedCustomer"];
            var model = new UserSessionHistory();
            var daccess = new ApplicationCommon.Ado.SqlDataAccess();
            var customerNamesDt = daccess.GetUserNames(customerId);
            var customerList = new List<UserSessionData>();
            for (var i = 0; i < customerNamesDt.Rows.Count; i++)
            {
                var userinfo = new UserSessionData();
                userinfo.CustomerId = customerNamesDt?.Rows[i]["Customer_Id"].ToString() ?? "";
                userinfo.CustomerName = customerNamesDt?.Rows[i]["Customer_Name"].ToString() ?? "";
                userinfo.UserId = customerNamesDt?.Rows[i]["User_ID"].ToString() ?? "";
                userinfo.UserName = customerNamesDt?.Rows[i]["UserName"].ToString() ?? "";
                customerList.Add(userinfo);
            }
            model.UserInfoList = customerList;
        return View(model);
    }

    [HttpPost]
    [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
    public JsonResult GetUserSessionHistory()
    {
        var draw = Request.Form.GetValues("draw").FirstOrDefault();
        var start = Request.Form.GetValues("start").FirstOrDefault();
        var length = Request.Form.GetValues("length").FirstOrDefault();
        if (Request["value1"] != null)
            Session["userId"] = Request["value1"]; 
        int pageSize = length != null ? Convert.ToInt32(length) : 0;
        try
        {
            var UserID = Convert.ToInt32(Session["userId"]);
            var filterModel = new FilterSessionHistoryModel();
            filterModel.UserID = UserID;
            filterModel.Skip = int.Parse(start);
            filterModel.Take = int.Parse(length);
            var fromDate = Request["FromDate"];
            var toDate = Request["ToDate"];
            filterModel.userSearch = Request["userSearch"];
            if (!string.IsNullOrEmpty(fromDate) && !string.IsNullOrEmpty(toDate))
            {
                filterModel.DateFrom = fromDate;
                filterModel.DateTo = toDate;
            }
            UserService userService = new UserService();
            List<ADM_User_Session_History_Result> SessionList = userService.ADM_User_Session_History(filterModel);
            int? numberOfRecords = 0;
            if(SessionList.Count>0) {
                numberOfRecords=SessionList[0].NumberOfRecords;
            }
            return Json(new { draw = draw, recordsFiltered = (int)numberOfRecords, recordsTotal = (int)numberOfRecords, data = SessionList }, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            CustomLogging.LogMessage(ex.Message + "/r/n" + ex.Source + "/r/n" + ex.StackTrace, LogType.Error);
            return this.GetJSONObject(false, ex.Message.ToString());
        }
    }

The hierarchy is like this. 1. The Admin user can use any customer 2. One customer can have many users 3. The table shows the time of log in of the user selected.

The problem is that the list through which the Admin can change the Customer is in the top nav present in _Layout.cshtml where as this data table is in another view. The data changes fine while cahanging the user but I need it to reload or get empty when the customer is changed.

old browsers like 'explorer' keep caching the info from a first ajax call, you can try to set the cash flag to false and the table will be updated each time

function ReLoadTable() {
        $.ajax({
            cache: false,
            url: 'Your URL',
            type: 'POST',

in controller put this attribute

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public class HomeController : Controller
{

finally in your Global.asax file add this function

protected void Application_PreSendRequestHeaders(Object sender, EventArgs e)
    {
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetAllowResponseInBrowserHistory(false);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM