Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!