Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
MVC Ajax prevent redirect to action controller

In my view I have a modal window, it have the next form...

@using (Html.BeginForm("controllerAction", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div class="container" id="editRecordForm">
        <div class="row">
            <div class="col-md-6">
                @Html.LabelFor(model => model.Author)
                @Html.TextBoxFor(model => model.Author, new { @class = "form-control", @style = "height:auto" })
                @Html.ValidationMessageFor(model => model.Author)
            </div>
        </div>
        <br/>
        <div class="row">
            <div class="col-md-6">
                @Html.LabelFor(model => model.Image)
                <input type="file" name="file" accept="image/*">
            </div>
        </div>
        <br />
        <input type="submit" value="Submit" class="btn btn-primary">
    </div>
}

this is the JS that contains the ajax request

<script>
    var formdata = new FormData($('form').get(0));
    $('form').submit(function () {
        if ($(this).valid()) {
            $.ajax({
                url: this.action,
                type: this.method,
                cache: false,
                data: formdata,
                success: function (status, data) {
                    console.log(data);
                }
            });
        }
        return false;
    });
</script>

The action controller receives two parameters the model and file

[HttpPost]
public async Task<JsonResult> controllerAction(HttpPostedFileBase file, Model model)
{
  var json = new
  {
      Success = true,
      StatusCode = "200",
      ErrorDesc = "OK",
      ErrorCode = "",
      NewId = ""
  };

  //some process

  return Json(json, JsonRequestBehavior.AllowGet);
}

The problem is why when the controller action finish, it redirects to the action controller url

http://controller/action 

and it does not stay on the same page?

What Im doing wrong?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You are not preventing the default action of the form.

$('form').submit(function (e) {
    e.preventDefault();
    if ($(this).valid()) {
        $.ajax({
            url: this.action,
            type: this.method,
            cache: false,
            data: formdata,
            success: function (status, data) {
                console.log(data);
            }
        });
    }
    return false;
});
about 4 years ago · Santiago Trujillo Relatório

0

The problem was the bad config on the javascript- ajax part

$('form').submit(function () {
    var formdata = new FormData($('form').get(0));
    if ($(this).valid()) {
        $.ajax({
            url: this.action,
            type: this.method,
            cache: false,
            processData: false,
            contentType: false,
            data: formdata,
            success: function (status, data) {
                console.log(data);
            }
        });
    }
    return false;
});

thanks to Stephen for the help.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda