Ajax POST does not execute the ASP.NET MVC action

1
  

Controller Action

public class EstabelecimentoController : ControllerBase
{
    [HttpPost]
    public ActionResult ImportarEstabelecimentos()
    {
        var file = Request.Files["inputFileImportarEstabelecimentos"];


        return RedirectToAction("Index");

    }
}
  

HTML input snippet

Importar <input id="inputFileImportarEstabelecimentos" name="inputFileImportarEstabelecimentos" type="file" onchange="ImportarEstabelecimentos()" />
  

javascript snippet

<script type="text/javascript">
$(document).ready(function () {

});
function ImportarEstabelecimentos() {

    $.ajax({
        type: "POST",
        url: "/Estabelecimento/ImportarEstabelecimentos",
        datatype: "JSON",
        contentType: "application/json; charset=utf-8",
        data: {},
        success: function() { alert('Success'); }

        });
}

    
asked by anonymous 15.06.2018 / 17:44

1 answer

0

You are not posting the file in the ajax request, so do:

var form = $("#ID_DO_SEU_FORM");
dataForm = new FormData(form[0]);//IE10+

When creating the url of your Action , do so: @Url.Action("NOME_DA_ACTION", "NOME_DA_CONTROLLER") In your case: @Url.Action("ImportarEstabelecimentos", "Estabelecimento")

Change the method as follows:

function ImportarEstabelecimentos() {
    var form = $("#ID_DO_SEU_FORM");
    dataForm = new FormData(form[0]);//IE10+

    $.ajax({
        url: '@Url.Action("ImportarEstabelecimentos", "Estabelecimento")',
        data: dataForm,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        success: function (data) {
            alert(data);
        }
    });

I hope I have helped!

    
28.06.2018 / 23:34