I have a piece of code that collects the values of the inputs in the HTML page and posts them to a handler using AJAX.
However, when sending by AJAX I get a 400 Bad Request error and the handler is not called.
Where I am going wrong?
$("#sendButton").click(function (event) {
event.preventDefault();
var userId = $("#userId").val();
var userName = $("#username").val();
var message = $("#message").val();
var groupId = $("#groupid").val();
var attachFile = $("#f").get(0).files;
var formData = new FormData();
formData.append("FileAttach", attachFile);
formData.append("UserId", userId);
formData.append("UserName", userName);
formData.append("Message", message);
formData.append("GroupId", groupId);
$.ajax({
type: "POST",
url: "Index?handler=SendMessage",
data: formData,
encyType: "multipart/form-data",
processData: false,
contentType: false
});
$("#message").val('').focus();
const element = document.getElementById("preChat");
element.scrollIntoView({ block: "end" });
});
This is handler code
public class InsertChatViewModel
{
public string UserId { get; set; }
public string GroupId { get; set; }
public string Message { get; set; }
public string UserName { get; set; }
public IFormFile FileAttach { get; set; }
}
public IActionResult OnPostSendMessage([FromForm] InsertChatViewModel model)
{
// It is not called here
return Page();
}