简体   繁体   中英

Why i keep getting 400 error while calling ajax datatable api from .net core controller?

cmjobprogress.js

    var JobdataTable;

$(document).ready(function () {
    loadJobDataTable();
});

function loadJobDataTable() {
    JobdataTable = $('#JobtblData').DataTable({
        "ajax": {
            "url": "/Admin/CMJobProgress/GetAll"
        },
        "columns": [
            { "data": "job_number" },
            { "data": "assign_from" },
            { "data": "assign)to" },
            { "data": "date_assign" },
            { "data": "job_action" },
            { "data": "remarks" },
            { "data": "type" },
            { "data": "division" }
        ]

    })
}

CMJobProgressController.cs

#region API Calls
        [ValidateAntiForgeryToken]
       [HttpGet]
       public IActionResult GetAll()
        {
            var allObj = _unitOfWork.cmJobProg.GetALL(j => j.JobNumber=="19950232"); 

            return Json(new { data = allObj });
        }

#endregion

Index.cshtml

@{

    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0 text-dark">Job Action</h1>
            </div><!-- /.col -->
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="cmd.html">Home</a></li>
                </ol>
            </div><!-- /.col -->
        </div><!-- /.row -->
        <div class="row mb-2">
            <div class="col-6 text-right">
            </div>
            <div class="col-6 text-right">
                <a class="btn btn-primary"><i class="fas fa-plus"></i> &nbsp; Create New Job</a>
            </div>
        </div>

    </div><!-- /.container-fluid -->
</div>

<section class="content">
    <div class="container-fluid">
        <div class="p-4 border rounded">
            <table id="JobtblData" class="table table-striped table-bordered" style="width:100%">
                <thead class="thead-dark">
                    <tr class="table-info">
                        <th>Job Number</th>
                        <th>Assign From</th>
                        <th>Assign To</th>
                        <th>Date Assign</th>
                        <th>Job Action</th>
                        <th>Remarks</th>
                        <th>Type</th>
                        <th>Division</th>


                    </tr>
                </thead>
            </table>
        </div>
    </div>
</section>


@section Scripts{

    <script src="~/js/cmjobprogress.js"></script>
}

CMJobProgress.cs

namespace LXG.Models
{
    [Table("CMJOBPROG", Schema = "LASIS")]
    public class CMJobProgress
    {
        [Required]
        [MaxLength(8)]
        [Display(Name = "Job Number")]
        [Column("JOB_NUMBER")]
        public string JobNumber { get; set; }

        [Display(Name = "Assign From")]
        [MaxLength(22)]
        [Column("ASSIGN_FROM")]
        public string AssignFrom { get; set; }

        [Display(Name = "Assign To")]
        [MaxLength(22)]
        [Column("ASSIGN_TO")]
        public string AssignTo { get; set; }

        [Column("DATE_ASSIGN")]
        public DateTime DateAssign { get; set; }

        [Display(Name = "Job Action")]
        [Range(0, 999)]
        [Column("JOB_ACTION")]
        public string JobAction { get; set; }

        [Display(Name = "Remarks")]
        [MaxLength(500)]
        [Column("REMARKS")]
        public string Remarks { get; set; }

        [Display(Name = "Job Type")]
        [Required]
        [MaxLength(2)]
        [Column("TYPE")]
        public string Type { get; set; }

        [MaxLength(2)]
        [Column("DIVISION")]
        public string Division { get; set; }

    }
}

ApplicationDbContext.cs

namespace LXG.DataAccess.Data
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseOracle(@"User Id=xxxxx;Password=xxxxx;Data Source=xx.xx.xx.xx:xxxx/xxxxx;");

            }
        }

       
        public DbSet<CMJobProgress> CMJOBPROG { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {


            modelBuilder.Entity<CMJobProgress>(builder =>
            {
                builder.HasNoKey();
                builder.ToTable("CMJOBPROG");
            });
        }
    }
}

Error i get:

DataTables warning: table id=JobtblData - Ajax error. For more information about this error, please see http://datatables.net/tn/7 .

Request URL: https://localhost:44382/Admin/CMJobProgress/GetAll?_=1602720362984 Request Method: GET Status Code: 400 Remote Address: [::1]:44382 Referrer Policy: strict-origin-when-cross-origin

Could anyone help me plese?

According to your controller codes, I found you have enabled the ValidateAntiForgeryToken for your api call.

But your datatable's ajax calls doesn't send the AntiForgery token as the header to the api , so that it shows 400 error.

To solve this issue, you should add the @Html.AntiForgeryToken() in the view and modify the cmjobprogress.js to get the token and send it to the api.

More details, you could refer to below codes:

View:

@{

    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0 text-dark">Job Action</h1>
            </div><!-- /.col -->
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="cmd.html">Home</a></li>
                </ol>
            </div><!-- /.col -->
        </div><!-- /.row -->
        <div class="row mb-2">
            <div class="col-6 text-right">
            </div>
            <div class="col-6 text-right">
                <a class="btn btn-primary"><i class="fas fa-plus"></i> &nbsp; Create New Job</a>
            </div>
        </div>

    </div><!-- /.container-fluid -->
</div>

<section class="content">
    <div class="container-fluid">
        <div class="p-4 border rounded">
            <table id="JobtblData" class="table table-striped table-bordered" style="width:100%">
                <thead class="thead-dark">
                    <tr class="table-info">
                        <th>Job Number</th>
                        <th>Assign From</th>
                        <th>Assign To</th>
                        <th>Date Assign</th>
                        <th>Job Action</th>
                        <th>Remarks</th>
                        <th>Type</th>
                        <th>Division</th>


                    </tr>
                </thead>
            </table>
        </div>
    </div>
</section>
@Html.AntiForgeryToken()

@section Scripts{

    <script src="~/js/cmjobprogress.js"></script>
}

cmjobprogress.js:

<script>

    var JobdataTable;

    $(document).ready(function () {
        loadJobDataTable();
    });

    function loadJobDataTable() {
        JobdataTable = $('#JobtblData').DataTable({
            "ajax": {
                "url": "/Admin/CMJobProgress/GetAll"
                'beforeSend': function (request) {
                    request.setRequestHeader("RequestVerificationToken", document.getElementsByName('__RequestVerificationToken')[0].value);
                }
             },
            "columns": [
                { "data": "job_number" },
                { "data": "assign_from" },
                { "data": "assign)to" },
                { "data": "date_assign" },
                { "data": "job_action" },
                { "data": "remarks" },
                { "data": "type" },
                { "data": "division" }
            ]

        })
    }
</script>
DataTables warning: table id=tblData - Requested unknown parameter 'jobnumber' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4

Thanks for your response Jaromanda and Brando. Now i get the some of the column data, but some i did not get it due to above error. Actually how to define the column data name of ajax.datatable? It is actually not the same as the model properties name.

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