Search code examples
c#jqueryasp.net-coreasp.net-core-webapihttp-status-code-400

ASP.NET Core 3.1 Web API with $.ajax--failed to load resource 400 error


I have a PartialView that is dynamically loaded with a button. When I click Save, the form is posted to API Controller, Bp. I get a 400 HTTP error: Failed to load resource. I have googled until I'm blue in the face and cannot find a solution. Typically the problem for me is that the JSON object posted does not match the C# class. I have similar code in another program that works but I do not see how the they differ significantly. Any help will be greatly appreciated.

enter image description here

EditBP.cshtml

@model BP
<div style="z-index: 999998; opacity: 0.65; filter: alpha(opacity=65); left: 0px; width: 100%; cursor: default;
    position: absolute; top: 0px; height: 100%; background-color: white">
</div>
<div style="border: 1px solid black; z-index: 999999; left: 5%; width: 90%; cursor: default; position: absolute;
    top: 1%; background-color: white">
    <div class="d-flex justify-content-between ed mb-3">
        <div class="p-2" style="font-size:x-large">Add/Edit Boilerplate</div>
        <div class="p-2" style="font-size:x-large"><button id="Close"><span class="glyphicon glyphicon-remove"></span></button></div>
    </div>
    <div class="d-sm-flex flex-sm-row">
        <div class="p-2" style="width:50%">
            @await Component.InvokeAsync("Boilerplate", new { user = User.Identity.Name })
        </div>
        <div class="p-2" style="width:50%">
            <form id="formBP" name="formBP" method="post" data-bpapi="@ViewBag.BpApi">
                <div class="form-group p-2 w280">
                    <select class="form-control" data-live-search="true" asp-for="BPCPTID" asp-items="ViewBag.StudyType" required></select>
                </div>
                <input asp-for="MDIDBP" type="hidden" value="@ViewBag.MD" />
                <div class="font-weight-bold p-2">CPT Procedure</div>
                <div><textArea asp-for="CPTProcedureBP" class="form-control" rows="10"></textArea></div>
                <div class="font-weight-bold p-2">
                    TechDescription
                    <span style="margin-left:25px">
                        <select class="form-control2" asp-for="AgeGroup" asp-items="ViewBag.Age"></select>
                    </span>
                </div>
                <div><textArea asp-for="TechDescriptionBP" class="w600 form-control" rows="10"></textArea></div>
                <div class="font-weight-bold p-2">
                    Impression&nbsp;
                    <span class="form-check-inline" style="margin-left:25px">
                        <label class="form-check-label">
                            <input type="checkbox" class="form-check-input" asp-for="Abnormal"><span style="vertical-align:baseline;font-weight:normal"> Abnormal</span>
                        </label>
                    </span>
                </div>
                <div><textArea asp-for="ImpressionBP" class="w600 form-control" rows="10"></textArea></div>
                <div>
                    <button id="btnSave" type="button" class="btn btn-outline-dark btn-lg">Save</button>&nbsp;
                    <button id="btnClr" type="button" class="btn btn-outline-dark btn-lg">Clear</button>&nbsp;
                    <span id="bpMsg" class="text-danger" style="font-size:large"></span>
                </div>
            </form>
            <input id="BPState" type="hidden" />
        </div>
    </div>
</div>

BpController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CNPLog.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace CNPLog.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Produces("application/json")]
    public class BpController : ControllerBase
    {
        private IEEGRepository repository;

        public BpController(IEEGRepository repo)
        {
            repository = repo;
        }
        [HttpPost]
        public IActionResult Post(BP bp)
        {
            int result = repository.SaveBP(bp);
            string msg = string.Empty;
            if (result > 0)
                msg = "Boilerplate saved.";
            else
                msg = "There was a problem saving boilerplate";
            return Ok(new { msg = msg });
        }
    }
}

snippet of script file with ajax code

var bpcptid = $('#BPCPTID').val();
var mdidbp = $('#MDIDBP').val();
var cptprocbp = $('#CPTProcedureBP').val();
var agegroup = $('#AgeGroup').val();
var techdesc = $('#TechDescriptionBP').val();
var abnormal = $('#Abnormal').val();
var imp = $('#Impression').val();
var bp = { BPCPTID: bpcptid, MDIDBP: mdidbp, CPTProcedureBP: cptprocbp, AgeGroup: agegroup, TechDescriptionBP: techdesc, Abnormal: abnormal, ImpressionBP: imp };
       
        $.ajax({
            url: urlBpApi,
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(bp),
            type: "POST",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("RequestVerificationToken",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
            },
            success: function(data) {
                $("#editBP").load(urlEditBP);
                $('#BPState').val(getBpSerialized());
            },
            error: function (xhr, status, errorMsg) {
                $('#bpMsg').html(errorMsg);
            }
        });

Here is the BP class

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace CNPLog.Models
{
    public enum Age : byte { DNA, Neonate, Infant, Child, Adult }
    public class BP
    {
        [Range(1, 256, ErrorMessage = "Please select a study type")]
        public int BPCPTID { get; set; }
        public string CPTDescription { get; set; }
        public int MDIDBP { get; set; }
        public Age AgeGroup { get; set; } = Age.DNA;
        public string StrAgeGroup => AgeGroup switch
        {
            Age.DNA => "N/A",
            Age.Neonate => "Neonate",
            Age.Infant => "Infant",
            Age.Child => "Child",
            Age.Adult => "Adult",
            _ => throw new ArgumentException(message: "invalid enum value", paramName: nameof(AgeGroup)),
        };
        public byte ByAge => AgeGroup switch
        {
            Age.DNA => (byte)Age.DNA,
            Age.Infant => (byte)Age.Infant,
            Age.Child => (byte)Age.Child,
            Age.Adult => (byte)Age.Adult,
            _ => throw new ArgumentException(message: "invalid enum value", paramName: nameof(AgeGroup)),
        };
        public bool Abnormal { get; set; } = false;
        public string StrAbnormal
        {
            get
            {
                return Abnormal == true ? "Abnormal" : "Normal";
            }
        }
        public string For { get; set; }
        public string CPTProcedureBP { get; set; }
        public string TechDescriptionBP { get; set; }
        public string ImpressionBP { get; set; }
        public string Msg { get; set; }
    }
}

Solution

  • For 400 error,that is because the data type in Ajax cannot match the model property correctly. It can be solved by changing the type in data.

    var bp = { BPCPTID: parseInt(bpcptid), MDIDBP: parseInt(mdidbp), CPTProcedureBP: cptprocbp, StrAgeGroup: agegroup, TechDescriptionBP: techdesc, Abnormal: Boolean(abnormal) , ImpressionBP: imp  };
    

    Result:

    enter image description here

    The code above could resolve the issue.But your js code still need to be modified :

    1.The checkbox value is always be true,you need to judge it if it is be checked or not,then get the value:

    var abnormal = $('#Abnormal').prop("checked") ? 1 : 0;
    

    2.There seems no element with id Impression but have element with id ImpressionBP,be sure it exists:

    var imp = $('#Impression').val();
    

    Update:

    You could also remove the [ApiController],and no need to change the js:

    [Route("api/[controller]")]
    
    //[ApiController]
    [Produces("application/json")]
    public class BpController : ControllerBase
    {}