Ajax POST does not execute the ASP.NET MVC action

Asked

Viewed 244 times

1

Controller Action

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


        return RedirectToAction("Index");

    }
}

Excerpt from the HTML input

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'); }

        });
}

  • Ajax is coming to the controller?

  • @Mayconf.Castro, exactly that the problem, Ajax is not giving error, but it does not enter my Controller Action

  • url puts url: Urlapplication + "/Establishment/Importestablishments"

  • 1

    @Mayconf.Castro, what would this Urlapplication be ?

  • can you open the url in the browser? if you are using Chrome, use dev tool (F12) and look at the flap Network to see the call and which answer is returned

  • It’s to get the local url

  • @Mayconf.Castro, very strange as no request works, I tried for other action and nothing, I changed post to get and also nothing..

  • Your ajax is being called?

  • The ajax is correct, maybe he’s not being called. Try to put some message in the function to be able to see it in the console, or try to put the event onchange by javascript code. $("#campo").on("change", function(){})

  • puts a . here: ./Estabelecimento/ImportarEstabelecimentos

  • Remove the datatype: "JSON", contentType: "application/json; charset=utf-8", if you’re not expecting a JSON as an answer.

Show 6 more comments

1 answer

0

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

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

When creating your url 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’ve helped!

Browser other questions tagged

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