Home > Enterprise >  ajax request from JavaScript to asp.net MVC core 6 controller not working
ajax request from JavaScript to asp.net MVC core 6 controller not working

Time:08-24

I am using asp.net core 6 to send JavaScript request to controller for adding data but its not responding and after data: command it jumps to error section

$.ajax({
    url: routeURL   '/api/Appointment/SaveCalendarData',
    type: 'Post',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    data: JSON.stringify(requestData),
    success: function (response) {
        if (response.status == 1) {
            console.log(response);
            //$notify(response.message, "success");
            onCloseModal();
        }
        else {
            console.log("Error");
            //$notify(response.message, "error");
        }
    },
    error: function () {
        console.log("Error error log");
    }
});

here is the request data from where data is coming from razor in request Data Function

function onSubmitForm() {
var requestData = {
    Id: parseInt($("#id").val()),
    Title: $("#title").val(),
    Description: $("#description").val(),
    StartDate: $("#appointmentDate").val(),
    Duration: $("#duration").val(),
    DoctorId: $("#doctorid").val(),
    PatientId: $("#patientId").val()
}
console.log(requestData);

and here is the controller side but JavaScript request doesn't hit controller side

    namespace AppointmentSchedule.Controllers.Api
{
    [Route("api/Appointment")]
    [ApiController]
    public class AppointmentApiController : Controller
    {
        private readonly IAppointmentService _appointmentService;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly string loginUserId;
        private readonly string role;
        public AppointmentApiController(IAppointmentService appointmentService, IHttpContextAccessor httpContextAccessor, string loginUserId)
        {
            _appointmentService = appointmentService;
            _httpContextAccessor = httpContextAccessor;
            loginUserId = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
            role = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.Role);
        }
        [HttpPost]
        [Route("SaveCalendarData")]
        public JsonResult SaveCalendarData(AppointmentVM data)
        {
            CommonResponse<int> commonResponse = new CommonResponse<int>();
            try
            {
                commonResponse.status = _appointmentService.AddUpdate(data).Result;
                if (commonResponse.status == 1) 
                {
                    commonResponse.message = Helper.Helper.appointmentUpdated;
                }
                if (commonResponse.status == 2)
                {
                    commonResponse.message = Helper.Helper.appointmentAdded;
                }
            }
            catch (Exception e)
            {
                commonResponse.message = e.Message;
                commonResponse.status = Helper.Helper.failure_code;
            }
            return Json(commonResponse);
        }
    }
}

and last its Program.cs file

    var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<ApplicationDbContext>(options=>options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Add services to the container.
builder.Services.AddTransient<IAppointmentService, AppointmentService>();
builder.Services.AddControllersWithViews();
builder.Services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddHttpContextAccessor();
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseDefaultFiles();
app.UseStaticFiles();


app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

here is the Network response error message where its throwing 500

CodePudding user response:

  1. Please check if there is any JS error in your browser console, If any please fix it accordingly.
  2. Check for the network response or status after the AJAX call, It'll give you a clue about the issue.
  3. If you get 405 status code maybe it's happening because of Antiforgery Token. If you don't want to validate the request just add [IgnoreAntiforgeryToken] in your action method, or provide the anti-forgery token during the Ajax call @Html.AntiForgeryToken()

Ex:

fetch(postUrl, {
        method: 'post',
        body: formData,
        headers: {
            'RequestVerificationToken': '@AntiForgery.GetAndStoreTokens(HttpContext).RequestToken'
        }
    }).then(function(response) {
        console.log(response);
    });

CodePudding user response:

Remove loginUserId from constructor parameters as follows:

 public AppointmentApiController(IAppointmentService appointmentService, IHttpContextAccessor httpContextAccessor)
 {
    _appointmentService = appointmentService;
    _httpContextAccessor = httpContextAccessor;
     loginUserId = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
     role = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.Role);
  }

CodePudding user response:

Try the code like below:

<input id="id" name="Id" />

<input id="title" name="Title" />

<button onclick="postdata1()">submit(jsondata)</button>

   <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript">
 function postdata1() {
 var a = [];            
 var requestData = { Id: parseInt($("#id").val()),Title: $("#title").val()};
 a.push(requestData);
var data = JSON.stringify(a);
$.ajax({
    url: '/api/Appointment/SaveCalendarData',
    type:  "POST",
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },   
    dataType: "json",
    data:data,
   }).done(function(data) {
            });
            }
    </script>

Add [FromBody] List<AppointmentVM> data in your action:

        [HttpPost]
        [Route("SaveCalendarData")]
        public JsonResult SaveCalendarData([FromBody] List<AppointmentVM> data)
        {
            ....//do your staff
        }

result:

enter image description here

  • Related