gpt4 book ai didi

c# - MVC Ajax 防止重定向到 Action Controller

转载 作者:太空宇宙 更新时间:2023-11-03 23:00:50 25 4
gpt4 key购买 nike

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

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

Action Controller 接收模型和文件两个参数

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

问题是为什么当 Controller Action 完成时,它会重定向到 Action Controller url

http://controller/action 

它不在同一页面上?

我做错了什么?

最佳答案

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

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

关于c# - MVC Ajax 防止重定向到 Action Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43150964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com