What is the correct way to send a form to a controller via AJAX?

2

I have a simple form, which is basically my ViewModel. I'm doing a post via AJAX passing this form, but on the server side, everything is always null. My AJAX is as follows:

var formData = $('form').serialize();
$.ajax({
    url: '/configuracaocomercial/Create',
    type: "post",
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    data: { viewModel: formData },
    success: function (data) {
        // meu callback
    }
});

I had read in a question in the SO in English, that the problem could be the contentType, so I put this 'application/x-www-form-urlencoded; charset=UTF-8' . However, my problem persists. On the server side, I get it simply:

[HttpPost]
public ResultadoAjax Create(ConfiguracaoComercialViewModelEdit viewModel)
{
    // Aqui, a viewModel já vem null
    // meu código
    // ...
    return result;
}
    
asked by anonymous 03.10.2017 / 18:14

2 answers

1

As far as I can see, there is an item that is in the way that is viewModel , I think you should do this:

Change this

var formData = $('form').serialize();
$.ajax({
    url: '/configuracaocomercial/Create',
    type: "post",
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    data: { viewModel: formData },
    success: function (data) {
        // meu callback
    }
});

why:

var formData = $('form').serialize();
$.ajax({
    url: '/configuracaocomercial/Create',
    type: "post",
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    data: formData,
    success: function (data) {
        // meu callback
    }
});
    
03.10.2017 / 18:25
1

Try to use the following command in the view:

@using (Ajax.BeginForm("ACTION", "CONTROLLER",
new AjaxOptions
{
    HttpMethod = "POST",
    OnBegin = "$.fn.ExibirLoading();",
    OnSuccess = "CarregarServicoTerceiroServicoComplete(data);",
    OnFailure = "$.fn.VerifyError(xhr, status, error);",
    OnComplete = "$.fn.OcultarLoading();$('#FormCadastrarServico')[0].reset();"
}, new { @id = "FormCadastrarServico" }))
                    {
    //SEU FORMULARIO    
}

And the .net will automatically call via ajax, I believe this is the best way.

The methods OnBegin , OnSuccess , OnFailure , OnComplete will call js for the actions mentioned.

    
03.10.2017 / 18:20