Problems serializing a form and making a Viewmodel Post using Ajax - Asp.net Core MVC

Asked

Viewed 40 times

0

I’m making a Submit using AJAX, but I’m having problems because it’s giving error 404 and I’ve tried to do several ways to use JSON.stringfy, use [Frombody] in the controller action, etc. Can anyone tell me what’s going wrong? When I do Submit normally (without using ajax), everything works normally, but with ajax, there seems to be some problem in the serialization and the way I pass the parameter (Viewmodel).

inserir a descrição da imagem aqui

VIEWMODEL:

public class CriarParcelasAutomaticamenteViewModel
{
    public int FinanceiroId { get; set; }
    public int QuantidadeParcelas { get; set; }
    public DateTime DataPrimeiroVencimento { get; set; }
    public decimal ValorDocumento { get; set; }
}

FULL CONTROLLER:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Retaguarda.Application.Interfaces;
using Retaguarda.Application.ViewModels.Financeiro.FinanceiroParcela;
using Retaguarda.Domain.Core.Notifications;

namespace Retaguarda.Presentation.Web.UI.MVC.Controllers
{
    [AllowAnonymous]
    public class FinanceiroParcelaController : BaseController
    {
        private readonly IFinanceiroParcelaAppService _financeiroParcelaAppService;
        private readonly ICriarParcelasAutomativamenteAppService _criarParcelasAutomativamenteAppService;

        public FinanceiroParcelaController(IFinanceiroParcelaAppService financeiroParcelaAppService,
                                 ICriarParcelasAutomativamenteAppService criarParcelasAutomativamenteAppService,
                                 INotificationHandler<DomainNotification> notifications) : base(notifications)
        {
            _financeiroParcelaAppService = financeiroParcelaAppService;
            _criarParcelasAutomativamenteAppService = criarParcelasAutomativamenteAppService;
        }
              

        [HttpGet]
        [Authorize(Policy = "CanWriteFinanceiroParcelaData")]
        [Route("financeiro-parcela-gerenciar/criar-financeiro-parcela-automaticamente/{financeiroId:int}")]
        public IActionResult CreateFinanceiroParcelaAutomaticamente(int financeiroId)
        {
            if (financeiroId == 0)
            {
                return NotFound();
            }

            return View(_criarParcelasAutomativamenteAppService.CreateNew(financeiroId));
        }

        [HttpPost]
        [Authorize(Policy = "CanWriteFinanceiroParcelaData")]
        [ValidateAntiForgeryToken]
        [Route("financeiro-parcela-gerenciar/criar-financeiro-parcela-automaticamente/{financeiroId:int}")]
        public IActionResult CreateFinanceiroParcelaAutomaticamente(CriarParcelasAutomaticamenteViewModel criarParcelasAutomaticamenteViewModel)
        {
            if (!ModelState.IsValid) return View(criarParcelasAutomaticamenteViewModel);

            var financeiroParcelasList = _financeiroParcelaAppService.CreateNewList(criarParcelasAutomaticamenteViewModel);
            if (financeiroParcelasList != null)
            {
                foreach (var financeiroParcela in financeiroParcelasList)
                {
                    int financeiroParcelaId = _financeiroParcelaAppService.Register(financeiroParcela);

                    if (!IsValidOperation())
                        return View(criarParcelasAutomaticamenteViewModel);
                }

                ViewBag.Sucesso = "Registros inseridos!";
            }

            return new EmptyResult();

            // return PartialView("~/Views/Financeiro/FinanceiroParcela/_FinanceiroParcelaGrid.cshtml", _financeiroParcelaAppService.CreateNewList(criarParcelasAutomaticamenteViewModel));
        }
    }
}

PROBLEMATIC ACTION:

[HttpPost]
[Authorize(Policy = "CanWriteFinanceiroParcelaData")]
[ValidateAntiForgeryToken]
[Route("financeiro-parcela-gerenciar/criar-financeiro-parcela-automaticamente/{financeiroId:int}")]
public IActionResult CreateFinanceiroParcelaAutomaticamente(CriarParcelasAutomaticamenteViewModel criarParcelasAutomaticamenteViewModel)
{
    if (!ModelState.IsValid) return View(criarParcelasAutomaticamenteViewModel);

    var financeiroParcelasList = _financeiroParcelaAppService.CreateNewList(criarParcelasAutomaticamenteViewModel);
    if (financeiroParcelasList != null)
    {
        foreach (var financeiroParcela in financeiroParcelasList)
        {
            int financeiroParcelaId = _financeiroParcelaAppService.Register(financeiroParcela);

            if (!IsValidOperation())
                return View(criarParcelasAutomaticamenteViewModel);
        }

        ViewBag.Sucesso = "Registros inseridos!";
    }

    return new EmptyResult();
}

AJAX:

$("#btn-criar-parcelas").on("click", function (e) {
    e.preventDefault();

    if ($('#frmCriarParcelasAutomaticamente').valid()) {
        //Desabilitar todos os elementos que estiverem bloqueados para poder efetuar o submit dos dados.
        $(':disabled').each(function (e) {
            $(this).removeAttr('disabled');
        });

        var valdata = $("#frmCriarParcelasAutomaticamente").serialize();

        $.ajax({
            url: "/financeiro-parcela-gerenciar/criar-financeiro-parcela-automaticamente",
            type: "POST",
            //dataType: 'json',
            //contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            data: valdata,
            traditional: true,
            success: function (data) {              

            },
            error: function () {
                stopLoadModalInside();
                alert("Oops! Algo deu errado.");
            }
        });
    }
});
  • Error 404 means No Found ie, not found your route depends on the controller by which is your controller?

  • @novic updated Post with Controller. There are two actions with the same names, but with the same route and different parameters. The second action is that I need to go viewmodel.

  • in the Route place a bar (Route("/financeiro-parcela-gerenciar/criar-financeiro-parcela-automaticamente")) test both !

  • Didn’t work @novic :(

  • makes the same mistake

  • Yes, you’re making the same mistake.

  • your route is wrong: /financeiro-parcela-gerenciar/criar-financeiro-parcela-automaticamente leaves so without the variable at the end now goes in the way with Httppost

  • Without the variable it worked!! : ) Aff, I don’t believe it!

  • works with the variable also only you have to pass? if you want to pass back the way it was

  • if you were wrong on the route ... you have to put the same is configured.

  • It works without the variable {financeiroId:int}. is that I have two actions with the same route and variable...

  • lack knowledge for you, you have two equal routes, but the verbs are different one is GET and the other is POST that also differentiates the routes

  • Only that there is a problem: When the Viewmodel is valid the action should not return anything. When viewmodel is not valid, then yes, it needs to return to viewmodel. I do not know how to treat this... I am using Return new Emptyresult(); which makes an error in the ajax request.. You would know how to treat this?

  • if you’ve ever done that if (!ModelState.IsValid) return View(criarParcelasAutomaticamenteViewModel);! so I don’t know what your problem is that it’s local

  • Never mind, I’ll take care of it later. If you want to comment with your answer that was the withdrawal of the variable {financeiroId:int}...I thank you for the help.

Show 10 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.