-1

I am getting a little frustrated, This same code works elsewhere in my project. For some reason it is not hitting the controller action. When page loads the datatable comes up and just has the processing popup like it cannot find the records. I put a breakpoint on the controller action and found it isn't even hitting it.

Javascript code:

 $(document).ready(function () {
    var oTableMenuPermission = "";
    $("#PartsListTable").dataTable({
        "ajax": {
            "url": "/Home/GetList",
            "type": "POST",
            "datatype": "json",              
        },
        "responsive": true,
        "bRetrieve": true,
        "bProcessing": true,
        "deferRender": true,
        "dom": 'lBfrtip',
        "serverSide": "true",
        "order": [0, "PartNumber"],
        "language": {
            "processing": "processing...Please wait"
        },
        "buttons": [
            { extend: 'copyHtml5', exportOptions: { columns: ':visible' } }
            , { extend: 'excelHtml5', exportOptions: { columns: ':visible' } }
            , { extend: 'csvHtml5', exportOptions: { columns: ':visible' } }
            , { extend: 'pdfHtml5', exportOptions: { columns: ':visible' } }
            , { extend: 'print', exportOptions: { columns: ':visible' } }
            , 'colvis'
        ],
        columnDefs: [{ orderable: false, targets: [2, 3, 4, 5, 6] }],

        "aoColumns": [
            { "data": "PartNumber", "name": "PartNumber" },
            {
                "data": "PartImage", "aTargets": [0],
                "render": function (data) {
                    if (data === null) return '<img src=Content/Images/Parts/NoImage.png style="width:50px;" />';
                    return '<img src=Content/Images/Parts/' + data + ' class="zoom" style="width:50px;" />';
                }
            },
            { "data": "Description", "name": "Description" },             
            {
                "data": "HasUpgrade", "aTargets": [0],
                "render": function (data) {
                    if (data === true) {
                        return '<b style="color:green;">Yes</b>';
                    } else {
                        return '<b style="color:red;">No</b>';
                    }
                }
            },
            {
                "data": "IsUpgrade", "aTargets": [0],
                "render": function (data) {
                    if (data === true) {
                        return '<b style="color:green;">Yes</b>';
                    } else {
                        return '<b style="color:red;">No</b>';
                    }
                }
            },
            {
                "mRender": function (oObj, type, full) {
                    var button = '<div>'
                    button += '<div class="btn-group">';
                    button += '<a class="btn btn-warning btn-sm" href="' + ControlerNameParts + "/Details/" + full.Material + '" data-ajax-update="#SkEdit" data-ajax-success="openModalDialog(\'SkEdit\', \'Edit\')" data-ajax-mode="replace" data-ajax-method="GET" data-ajax-failure="clearModalDialog(\'SkEdit\');alert(\'Ajax call failed\')" data-ajax-begin="prepareModalDialog(\'SkEdit\')" data-ajax="true">Details</a>&nbsp;';
                    button += '</div></div>';
                    return button;
                }
            },

        ],


    });
});

And here is the controller action:

        [HttpPost]
    public ActionResult GetList()
    {
        // Server Side Parameters
        int start = Convert.ToInt32(Request["start"]);
        int length = Convert.ToInt32(Request["length"]);
        string searchValue = Request["search[value]"];
        string sortColumnName = Request["column[" + Request["order[0][column]"] + "][name]"];
        string sortDirection = Request["order[0][dir]"];

        List<PartSearchView> prodList = new List<PartSearchView>();
        using (GeneralEntities db = new GeneralEntities())
        {
            prodList = db.PartSearchView.ToList();
            int totalRows = prodList.Count;
            if (!string.IsNullOrEmpty(searchValue))
            {
                prodList = prodList.Where(x => x.PartNumber != null && x.PartNumber.ToLower().Contains(searchValue.ToLower())).ToList();
            }

            int totalRowsAfterFilteing = prodList.Count;
            // Sorting
            prodList = prodList.OrderBy(sortColumnName + " " + sortDirection).ToList<PartSearchView>();

            prodList = prodList.Skip(start).Take(length).ToList();

            return Json(new { data = prodList, draw = Request["draw"], recordsTotal = totalRows, recordsFiltered = totalRowsAfterFilteing }, JsonRequestBehavior.AllowGet);
        }

    }

I have tried changing the url to a @Url.Action("GetList", "Home").

It may have something to do with routing, but I cannot see anywhere in my route config where there is a problem. I tried to go directly to the Url and it pulls a 404 page, unlike the one that is working which does fault but also hits the controller action.

Thanks for your help!

UPDATE: Below is my route config. I changed the name of the page and the controller Action to be PartSearch before it was just Parts. Still same issue. This is part of the Home Controller.

 public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        // routes.MapRoute(
        //    name: "Roles",
        //    url: "Roles/{action}/{id}",
        //    defaults: new { controller = "UserAndRole", action = "Index", id = UrlParameter.Optional }
        //);

        routes.MapRoute(
            name: "About",
            url: "About",
            defaults: new { controller = "Home", action = "About" }
        );

        routes.MapRoute(
            name: "Services",
            url: "Services",
            defaults: new { controller = "Home", action = "Services" }
        );

        routes.MapRoute(
           name: "Contact",
           url: "Contact",
           defaults: new { controller = "Home", action = "Contact" }
       );

        routes.MapRoute(
        name: "Quote",
        url: "Quote",
        defaults: new { controller = "Home", action = "Quote" }
       );

        routes.MapRoute(
         name: "MyEquipment",
         url: "MyEquipment/{id}",
         defaults: new { controller = "MyEquipment", action = "Index" }
        );

       // routes.MapRoute(
       // name: "PartsSearch",
       // url: "Parts",
       // defaults: new { controller = "Home", action = "Parts" }
       //);

        routes.MapRoute(
         name: "MyEquipmentTlj",
         url: "MyEquipment/Parts/{id}",
         defaults: new { controller = "MyEquipment", action = "Parts" }
        );

        // routes.MapRoute(
        // name: "Dashboard",
        //    url: "Dashboard/{id}",
        //    defaults: new { controller = "Dashboard", action = "Index", page = UrlParameter.Optional }
        //);

        routes.MapRoute(
        name: "EquipCat",
           url: "Equipment/Category/{slug}/{Catid}",
           defaults: new { controller = "Equipment", action = "Index", page = UrlParameter.Optional }
       );
        routes.MapRoute(
          name: "EquipTag",
          url: "Equipment/Tag/{slug}/{Tagid}",
          defaults: new { controller = "Equipment", action = "Index", page = UrlParameter.Optional }
      );

        routes.MapRoute(
            name: "EquipPost",
            url: "Equipment/Post/{id}/{slug}",
            defaults: new { controller = "Equipment", action = "Post" }
        );

        routes.MapRoute(
            name: "AddUsers",
            url: "Users/Create/{CompanyId}/{AddressId}",
            defaults: new { controller = "Users", action = "Create" }
        );

        routes.MapRoute(
            name: "BestenAddUsers",
            url: "UsersManager/Create/{CompanyId}/{AddressId}",
            defaults: new { controller = "UsersManager", action = "Create" }
        );

        routes.MapRoute(
            name: "AddMachines",
            url: "Machine/Add/{CompanyId}/{AddressId}",
            defaults: new { controller = "Machine", action = "Add" }
        );
        routes.MapRoute(
         name: "EventManagerAdd",
         url: "CalendarManager/Add/{companyId}/{addressId}",
         defaults: new { controller = "CalendarManager", action = "Add" }
       );

        routes.MapRoute(
           name: "ListAddresses",
           url: "Addresses/{id}",
           defaults: new { controller = "Addresses", action = "Index" }
       );

        routes.MapRoute(
           name: "ListOrders",
           url: "Orders/{id}",
           defaults: new { controller = "Orders", action = "Index" }
       );

        routes.MapRoute(
            name: "UserCreate",
            url: "Users/create/{CompanyId}/{AddressId}",
            defaults: new { controller = "Users", action = "Create"}
        );

        routes.MapRoute(
            name: "NotesAdd",
            url: "Notes/Add/{CompanyId}/{AddressId}",
            defaults: new { controller = "Notes", action = "Add" }
        );

        routes.MapRoute(
            name: "SerialAdd",
            url: "SerialNumbers/AddSerial/{SerialNumber}/{CompanyId}/{AddressId}",
            defaults: new { controller = "SerialNumbers", action = "AddSerial" }
        );

        routes.MapRoute(
           name: "SerialSearch",
           url: "SerialSearch",
           defaults: new { controller = "Home", action = "SerialSearch" }
       );

        routes.MapRoute(
           name: "ExpensesAdd",
           url: "ExpenseReports/Create/{CompanyId}/{AddressId}",
           defaults: new { controller = "ExpenseReports", action = "Create" }
       );

        routes.MapRoute(
           name: "InvoiceList",
           url: "Invoice/{cmpid}",
           defaults: new { controller = "Invoice", action = "Index" }
       );

        routes.MapRoute(
           name: "BInvoiceList",
           url: "InvoiceManager/{cmpid}",
           defaults: new { controller = "InvoiceManager", action = "Index", cmpid = UrlParameter.Optional }
       );

       routes.MapRoute(
           name: "CInvoiceList",
           url: "InvoiceManager/List/{addid}",
           defaults: new { controller = "InvoiceManager", action = "List" }
       );

        routes.MapRoute(
           name: "QuoteList",
           url: "Quotes/{cmpid}",
           defaults: new { controller = "Quotes", action = "Index" }
       );

        routes.MapRoute(
         name: "PurchaseOrderAdd",
         url: "PurchaseOrder/Add/{id}/{RFQID}",
         defaults: new { controller = "PurchaseOrder", action = "Add" }
     );

        routes.MapRoute(
          name: "Subjobs",
          url: "SubJobs/{id}",
          defaults: new { controller = "SubJobs", action = "Index" }
      );

        routes.MapRoute(
           name: "BQuoteList",
           url: "QuotePdfManager/{cmpid}",
           defaults: new { controller = "QuotePdfManager", action = "Index", cmpid = UrlParameter.Optional }
       );

        routes.MapRoute(
            name: "CQuoteList",
            url: "QuotePdfManager/List/{addid}",
            defaults: new { controller = "QuotePdfManager", action = "List" }
        );

        routes.MapRoute(
            name: "ConfirmEmail",
            url: "Account/SendEmailConfirm/{UserName}",
            defaults: new { controller = "Account", action = "SendEmailConfirm" }
        );

        routes.MapRoute(
            name: "ShippingAdd",
            url: "ShippingOrBOLs/Add/{companyId}/{addressId}/{orderId}",
            defaults: new { controller = "ShippingOrBOLs", action = "Add" }
        );
       
        routes.MapRoute(
           name: "EventAdd",
           url: "Calendar/{companyId}/{addressId}",
           defaults: new { controller = "Calendar", action = "Index" }
       );

        routes.MapRoute(
          name: "MessagesAdd",
          url: "Messages/Add/{user}",
          defaults: new { controller = "Messages", action = "Add" }
      );

        routes.MapRoute(
           name: "PastDue",
           url: "InvoiceManager/PastDue/{id}/{pastdue}",
           defaults: new { controller = "InvoiceManager", action = "PastDue" }
       );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

I changed the name because I have a PartsController. PartsController is used in the backend and has login credentials required. So I couldnt use it for this.

UPDATE:

I have found my issue. As silly as this may seem, the whole reason this was not hitting the controller was because in the line where I have columnDefs: [{ orderable: false, targets: [2, 3, 4, 5, 6] }], There was 1 to may, there are 6 columns but I forgot to count the first one as 0. I have caught this before in the past while using a foreach statement instead of server side because the formatting does not appear on load - meaning buttons, search, number of records, etc. But still populates the records. In server side it faults before record generation I guess. So it had nothing to do with routing at all. And the error that I was getting, i did not think that it had anything to do with it as it stated something about style. I found the answer on the dataTables forum. Thank you for everyone who helped out on this.

Scott Purtan
  • 237
  • 1
  • 10
  • "I tried to go directly to the Url and it pulls a 404 page" - so in short: Your URL "/Home/GetList" returns 404 and your action is not called. It would help, if you add information about your routing setup (most other code in your post will not help to solve this). E.g. routing part in Startup.cs, controller name + controller routing attributes. – Christoph Lütjen Sep 18 '21 at 22:46
  • This may help: https://stackoverflow.com/questions/28435734/how-to-get-a-list-of-all-routes-in-asp-net-core – Christoph Lütjen Sep 18 '21 at 22:47
  • This DataTables option looks odd: `"order": [0, "PartNumber"]`. I would expect it to be `"order": [0, "asc"]` or `"order": [0, "desc"]`. Ssee [here](https://datatables.net/reference/option/order). – andrewJames Sep 19 '21 at 00:19
  • @andrewjames yeah I am not sure why i did that but it is like that in the other page that works. It has been a while since I wrote the code. But you are right it shouldn't be that way. It probably just skips over it in the code that works. Meaning it doesn't hinder it, it just isn't sorting. Ill change it to see if it makes a difference. – Scott Purtan Sep 19 '21 at 00:47
  • You are right: DataTables tends to ignore unknown options (not always, but often). So, this is not a solution for your problem, but it should be corrected. – andrewJames Sep 19 '21 at 00:49

1 Answers1

0

you don't need post action for GetList since you don't send any parameters. Remove [post] and just for test try attribute routing

Add this to your config after IgnoreRoute

 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapMvcAttributeRoutes();

and controller

[Route("~/home/getlist")]
public ActionResult GetList()

and just IMHO chahge "type": "POST" to "GET" in ajax.

Serge
  • 40,935
  • 4
  • 18
  • 45
  • I did try that before under Parts and it did not make a difference. When i changed it to PartSearch and removed the [HttpPost] i could navigate to it and it hits the controller. I just changed it in the chtml view ajax to GET. And it still does not hit the controller. I added the route to the controller as you stated and still doesnt hit the controller, I can go directly to it, but the ajax doesnt hit it. – Scott Purtan Sep 18 '21 at 23:29
  • Just to note: When you use `"serverSide": "true"`, parameters are [automatically sent](https://datatables.net/manual/server-side#Sent-parameters) from DataTable to the server. These are used so that the server knows how to perform sorting, filtering and paging. But, yes, having said that, this does not mean you _need_ to use `POST`. You can certainly use `GET`. – andrewJames Sep 18 '21 at 23:30
  • @ScottPurtan I am sorry but what Parts have to do with getlist? What url you use to go directly? – Serge Sep 18 '21 at 23:31
  • @serge I had the page named Parts before and i changed it to PartSearch. I use the Url /Home/GetList to go directly to it. And it does go to it but also faults out because it is looking for a parameter - searchValue, it exists in the datatable but not if you go directly to the action without using the chtml page to get to it. I did use get and now have changed the name to GetGrid. Still doesn't work. – Scott Purtan Sep 18 '21 at 23:40
  • @ScottPurtan I am sorry , I didn' t notice that you are using old version. I updated my answer. Add attribute routing to your route config. – Serge Sep 18 '21 at 23:41
  • @Serge Yeah still nothing. I am not sure why routing is having such an issue with this. I have had issues in the past with pages not coming up because if the order I had them in the route config. Something is not right, I just cannot see where that is.. I have not changed anything in the route config, other than just now what you had me put in there.. – Scott Purtan Sep 18 '21 at 23:47
  • @ScottPurtan It means tha ajax is not triggering. Did you check developer tools of your browser? Usually Console tab. It shoud show javascript errors – Serge Sep 18 '21 at 23:58
  • @Serge No there is nothing in the console window that involves this case. I may have to go through my route config and comment out each one, one at a time to find out what the issue is. – Scott Purtan Sep 19 '21 at 00:42
  • @ScottPurtan You still didn't answer what url is working manually – Serge Sep 19 '21 at 00:48
  • @Serge yes i did it is up in one of the comments.. /Home/GetList will hit the controller. – Scott Purtan Sep 19 '21 at 01:26
  • But what is the first part? – Serge Sep 19 '21 at 01:28
  • @Serge http://localhost:59890/ – Scott Purtan Sep 19 '21 at 02:05
  • @Serge I tried putting the full Url in and it didn't make a difference. Its like it is ignoring the url.. Or ajax.. – Scott Purtan Sep 19 '21 at 02:07
  • @Serge - posted an update as to what the problem was. Actually no one would of found this because I did not post the table structure. My bad.. – Scott Purtan Sep 22 '21 at 00:05