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();
3
Answers
[IgnoreAntiforgeryToken]
in your action method, or provide the anti-forgery token during the Ajax call@Html.AntiForgeryToken()
Ex:
Try the code like below:
Add
[FromBody] List<AppointmentVM> data
in your action:result:
Remove
loginUserId
from constructor parameters as follows: