I created a method to perform a Insert
through Ajax
, like this:
function SalvarHorario()
{
//NomeHorario
var nome = $("#Nome").val();
var token = $('input[name="__RequestVerificationToken"]').val();
var tokenadr =
$('form[action="/Horario/Create"] input[name="__RequestVerificationToken"]').val();
var headers = {};
var headersadr = {};
headers['__RequestVerificationToken'] = token;
headersadr['__RequestVerificationToken'] = tokenadr;
//Gravar
var url = "/Horario/Create";
$.ajax({
url: url
, type: 'POST'
, headers: headersadr
, data: { Id: 0, Nome: nome, __RequestVerificationToken: token }
, success: function (data) {
//if (data.Resultado > 0) {
ListarItens(data.Resultado);
//}
}
});
}
But it does not recognize the CREATE method that I call in Action, the page I'm getting the data from, was created by Razor CRUD. It only includes through the automatic class that is created:
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
_context.Horarios.Add(Horarios);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
I created a controller, and I need it to search the method of this controller, I tried to change its name, and nothing is right, it follows what method I need it to call:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Horarios h)
{
if (ModelState.IsValid)
{
_context.Horarios.Add(h);
_context.SaveChanges();
}
return Json(new { Resultado = h.Id });
}
What am I doing wrong? If I take this code public async Task<IActionResult> OnPostAsync()
it returns me Bad Request 400 error.
I've tried several ways none works, I'm learning MVC Core Entity Framework
now, so I'm still getting a lot.