MVC Ajax阻止重定向到动作控制器

时间:2017-03-31 23:21:25

标签: c# jquery ajax asp.net-mvc

在我看来,我有一个模态窗口,它有下一个窗体......

@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>
}

这是包含ajax请求的JS

<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>

动作控制器接收模型和文件的两个参数

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

问题是当控制器操作完成时,它会重定向到动作控制器URL

http://controller/action 

它不会停留在同一页面上?

我做错了什么?

2 个答案:

答案 0 :(得分:2)

您没有阻止表单的默认操作。

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

答案 1 :(得分:1)

问题是javascript-ajax部分的错误配置

$('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;
});
感谢Stephen的帮助。