简体   繁体   中英

500 Internal Server Error Asp.net C# Datatables

I've MVC 5 asp.net C# Project Inventory and Restaurant, when I use Datatable inside my project here's my html:

   <table class="table table-striped table-bordered table-hover" id="dataTables-example">
        <thead>
            <tr>
                <th>
                    @Resources.Tokens_Admin.Name
                </th>
                <th>
                    @Resources.Tokens_Admin.Category
                </th>
                <th>
                    @Resources.Tokens_Admin.Price
                </th>
                <th>
                    @Resources.Tokens_Admin.Image
                </th>
                <th>

                </th>
             </tr>
        </thead>
        <tfoot>
        </tfoot>
    </table>

and JavaScripts:

<script>
    $(document).ready(function () {
        $("#dataTables-example").DataTable({
            "ajax": {`enter code here`
                "url": "/Meals/GetMealsList",
                "type": "POST",
                "datatype": "json"
            },
            "columns": [
                   { "data": "Name", "name": "Name" },
                   { "data": "CatId", "name": "CatId" },                      
                   { "data": "Price", "name": "Price" },
                   { "data": "Image", "name": "Image" },
                   {
                       "data": "Id", "render": function (Id, type, full, meta) {
                           debugger
                           return '<a href="#" onclick="Edit(' + Id + ')"><i class="glyphicon glyphicon-pencil"></i></a>'
                  }

                   }
            ],
            "serverSide": "true",
            "order": [0, "asc"],
            "processing": "true",
            "language": {
                "processing": "processing...please wait"
            }
        });
    });
</script>

and the Controller:

  [HttpPost]
          public ActionResult GetMealsList()
    {
        // server-side parameters
        int start = Convert.ToInt32(Request["start"]);
        int length = Convert.ToInt32(Request["length"]);
        string searchval = Request["search[value]"];
        string sortColumnName = Request["columns[" + Request["order[0][column]"] + "][name]"];
        string sortDirection = Request["order[0][dir]"];
        var MealList = db.Meals.ToList();
        int totalrows = MealList.Count();
        if (!string.IsNullOrEmpty(searchval))
        {
            MealList = MealList.Where(x => x.Price.ToString().Contains(searchval.ToLower()) || x.Category.Name.ToLower().Contains(searchval.ToLower())
            || x.Name.ToLower().Contains(searchval.ToLower())).ToList();
        }
        int totalrowsafterfiltering = MealList.Count();
        // sorting
        MealList = MealList.OrderBy(sortColumnName + " " + sortDirection).ToList();

        //paging
        MealList = MealList.Skip(start).Take(length).ToList();

        return Json(new { data = MealList, draw = Request["draw"], recordsTotal = totalrows, recordsFiltered = totalrowsafterfiltering }, JsonRequestBehavior.AllowGet);
    }

when I run the view Index I've an Internal Server Error 500. The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly. Requested URL: /Meals/GetMealsList can anyone help please?

First I think changing your line in Javascript:

"url": "/Meals/GetMealsList",

to

"url": "@Url.Action("GetMealsList", "Meals")",

should fix it. I'm assuming your controller is called MealsController ?

Second, I'd recommend doing something like the following, where you create ViewModels that represent the data that datatables is passing back, that should make your life a lot easier than how you're referencing the Request object as it should, using model binding, map the json data to your model.

Note, you shouldn't need the Newtonsoft.Json.JsonProperty lines, I just copied this code from a project where it had that already (related to a webapi).

    public class DataTablesSearchModel
    {
        // properties are not capital due to json mapping
        [Newtonsoft.Json.JsonProperty(PropertyName = "draw")]
        public int Draw { get; set; }

        [Newtonsoft.Json.JsonProperty(PropertyName = "start")]
        public int Start { get; set; }

        [Newtonsoft.Json.JsonProperty(PropertyName = "length")]
        public int Length { get; set; }

        [Newtonsoft.Json.JsonProperty(PropertyName = "columns")]
        public List<Column> Columns { get; set; }

        [Newtonsoft.Json.JsonProperty(PropertyName = "search")]
        public Search Search { get; set; }

        [Newtonsoft.Json.JsonProperty(PropertyName = "order")]
        public List<Order> Order { get; set; }
    }

    public class Column
    {
        [Newtonsoft.Json.JsonProperty(PropertyName = "data")]
        public string Data { get; set; }

        [Newtonsoft.Json.JsonProperty(PropertyName = "name")]
        public string Name { get; set; }

        [Newtonsoft.Json.JsonProperty(PropertyName = "searchable")]
        public bool Searchable { get; set; }

        [Newtonsoft.Json.JsonProperty(PropertyName = "orderable")]
        public bool Orderable { get; set; }

        [Newtonsoft.Json.JsonProperty(PropertyName = "search")]
        public Search Search { get; set; }
    }

    public class Search
    {
        [Newtonsoft.Json.JsonProperty(PropertyName = "value")]
        public string Value { get; set; }

        [Newtonsoft.Json.JsonProperty(PropertyName = "regex")]
        public string Regex { get; set; }
    }

    public class Order
    {
        [Newtonsoft.Json.JsonProperty(PropertyName = "column")]
        public int Column { get; set; }

        [Newtonsoft.Json.JsonProperty(PropertyName = "dir")]
        public string Dir { get; set; }
    }

Then your controller action looks like this:

[HttpPost]
      public ActionResult GetMealsList(DataTablesSearchModel model)
{
     //Access model for the data passed by datatables.
}

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