Ajax вызов не попадает на путь URL в контроллере / действии - PullRequest
0 голосов
/ 11 января 2020

Я пытаюсь следовать инструкции по созданию таблицы crud по этой ссылке http://www.dotnetawesome.com/2016/12/crud-operation-using-datatables-aspnet-mvc.html.

Однако я застрял, так как мой вызов Ajax не соответствует пути URL в контроллере / действии

это код для моей таблицы

<h2>Part 1 : Implement jQuery Datatable in ASP.NET MVC</h2>
<div style="width:90%; margin:0 auto" class="tablecontainer">
    <a class="popup btn btn-primary" href="/InventoryLocation/Save/0" style="margin-bottom:20px; margin-top:20px;">Add New Employee</a>
    <table id="myDatatable">
        <thead>
            <tr>
                <th>ID</th>
                <th>Armario</th>
                <th>Cajon</th>
            </tr>
        </thead>
    </table>
</div>


<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script>
    $(document).ready(function () {
        var oTable = $('#myDatatable').DataTable({
            "ajax": {
                "url": '/InventoryLocation/GetEmployees',
                "type": "get",
                "datatype": "json"
            },
            "columns": [
                { "data": "ubicacion_id", "autoWidth": true },
                { "data": "armario", "autoWidth": true },
                { "data": "cajon", "autoWidth": true },
                {
                    "data": "ubicacion_id", "width": "50px", "render": function (data) {
                        return '<a class="popup" href="/InventoryLocation/Save/' + data + '">Edit</a>';
                    }
                },
                {
                    "data": "ubicacion_id", "width": "50px", "render": function (data) {
                        return '<a class="popup" href="/InventoryLocation/Delete/' + data + '">Delete</a>';
                    }
                }
            ]
        })
        $('.tablecontainer').on('click', 'a.popup', function (e) {
            e.preventDefault();
            OpenPopup($(this).attr('href'));
        })
        function OpenPopup(pageUrl) {
            var $pageContent = $('<div/>');
            $pageContent.load(pageUrl, function () {
                $('#popupForm', $pageContent).removeData('validator');
                $('#popupForm', $pageContent).removeData('unobtrusiveValidation');
                $.validator.unobtrusive.parse('form');

            });

            $dialog = $('<div class="popupWindow" style="overflow:auto"></div>')
                .html($pageContent)
                .dialog({
                    draggable: false,
                    autoOpen: false,
                    resizable: false,
                    model: true,
                    title: 'Popup Dialog',
                    height: 550,
                    width: 600,
                    close: function () {
                        $dialog.dialog('destroy').remove();
                    }
                })

            $('.popupWindow').on('submit', '#popupForm', function (e) {
                var url = $('#popupForm')[0].action;
                $.ajax({
                    type: "POST",
                    url: url,
                    data: $('#popupForm').serialize(),
                    success: function (data) {
                        if (data.status) {
                            $dialog.dialog('close');
                            oTable.ajax.reload();
                        }
                    }
                })

                e.preventDefault();
            })
            $dialog.dialog('open');
        }
    })
</script>

И это имя контроллера, который не получает удара, когда я помещаю туда отладчик, он ничего не делает

public ActionResult GetEmployees()
{
    InventoryLocationContext inventoryLocation = new InventoryLocationContext();
    var inventoLocationData = inventoryLocation.GetAllInvenotryLocation().OrderBy(a => a.armario).ToList();
    return Json(new { data = inventoLocationData }, JsonRequestBehavior.AllowGet);            
}

Это имя моего контроллера, которое я скопировал, вставил его, чтобы убедиться, что оно имеет точное имя.

InventoryLocationController.cs

И вот код.

using CustomAuthorizationFilter.Infrastructure;
using erp_colombia.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace erp_colombia.Controllers
{
    public class InventoryLocationController : Controller
    {

        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public JsonResult GetEmployees()
        {
            InventoryLocationContext inventoryLocation = new InventoryLocationContext();
            var jsonData = new
            {
                jsonData = inventoryLocation.GetAllInvenotryLocation().OrderBy(a => a.armario).ToList()
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }


        [HttpGet]
        public ActionResult Save(int id)
        {
            InventoryLocationContext inventoryLocationContext = new InventoryLocationContext();

            var v = inventoryLocationContext.GetAllInvenotryLocation().Where(a => a.ubicacion_id == id).FirstOrDefault();
            return View(v);            
        }


        [HttpPost]
        public ActionResult Save(InventoryLocation emp)
        {
            InventoryLocationContext inventoryLocationContext = new InventoryLocationContext();

            bool status = false;
            if (ModelState.IsValid)
            {
                    if (emp.ubicacion_id > 0)
                    {
                        //Edit 
                        var v = inventoryLocationContext.GetAllInvenotryLocation().Where(a => a.ubicacion_id == emp.ubicacion_id).FirstOrDefault();
                        if (v != null)
                        {
                            v.armario = emp.armario;
                            v.cajon = emp.cajon;
                        }
                    }
                    else
                    {
                        //Save
                        inventoryLocationContext.updateToDB(emp);
                    }
                    status = true;              
            }
            return new JsonResult { Data = new { status = status } };
        }

        [HttpGet]
        public ActionResult Delete(int id)
        {
            InventoryLocationContext inventoryLocationContext = new InventoryLocationContext();
            var v = inventoryLocationContext.GetAllInvenotryLocation().Where(a => a.ubicacion_id == id).FirstOrDefault();
                if (v != null)
                {
                    return View(v);
                }
                else
                {
                    return HttpNotFound();
                }            
        }


    }
}

А вот мой код маршрутаconfig

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

А вот изображение моих файлов

my filese

Это jquery предупреждения, которые я получаю в firefox. Warnings

Любая помощь будет очень ценной

1 Ответ

1 голос
/ 11 января 2020

Сделав так, ваша проблема будет исправлена ​​

попробуйте изменить код контроллера на

[HttpGet]
public JsonResult GetEmployees()
{
  var jsonData = new
  {
   data = inventoryLocation.GetAllInvenotryLocation().OrderBy(a => 
   a.armario).ToList();
   };
    return Json(jsonData, JsonRequestBehavior.AllowGet);
}

и добавьте эти js в ваше представление или в _layout

<script src="Scripts/jquery-1.11.3.min.js"></script>
<script src="Scripts/jquery.dataTables.js"></script>
<link href="css/jquery.dataTables.min.css" rel="stylesheet" />

и в вашем js

добавьте вот так для инициализации данных

var oTable = $('#myDatatable').DataTable({
        "searching": true,
        "processing": true, // for show progress bar  
        "serverSide": true, // for process server side  
        "filter": true, // this is for disable filter (search box) 
        "ordering": true,
        "pagingType": "full_numbers",
        "ajax": {
            "url": '/InventoryLocation/GetEmployees',
            "type": "get",
            "datatype": "json"
        },
        "columns": [
            { "data": "ubicacion_id", "autoWidth": true },
            { "data": "armario", "autoWidth": true },
            { "data": "cajon", "autoWidth": true },
            {
                "data": "ubicacion_id", "width": "50px", "render": function (data) {
                    return '<a class="popup" href="/InventoryLocation/Save/' + data + 
                 '">Edit</a>';
                }
            },
            {
                "data": "ubicacion_id", "width": "50px", "render": function (data) {
                    return '<a class="popup" href="/InventoryLocation/Delete/' + data 
                  + '">Delete</a>';
                }
            }
        ]
    })
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...