我有一个基本表单,其中有几个文本字段和 Bootstrap 模式对话框(Bootstrap 4)上的文件上传 Controller 。下面是我的代码:
型号:
public class DemoContent
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[RegularExpression("([0-9]+)",ErrorMessage = "Age must be numbers only")]
public int Age { get; set; }
[EmailAddress]
public string Email { get; set; }
[DataType(DataType.Upload)]
[Display(Name = "Image")]
public HttpPostedFileBase ImageUrl { get; set; }
}
JavaScript
$(function() {
$("a[data-modal=demoPopup]").on("click", function () {
$("#demoModalContent").load(this.href, function () {
$("#demoModal").modal({ keyboard: true }, "show");
$("#demoForm").submit(function () {
if ($("#demoForm").valid()) {
var files = $("ImageUrl").get(0).files;
var data = $(this).serialize();
data.append("ImageUrl", files[0]);
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$("#demoModal").modal("hide");
location.reload();
} else {
$("#MessageToClient").text(result.message);
}
},
error: function () {
$("#MessageToClient").text("The web server had an error.");
}
});
return false;
}
});
});
return false;
});
Controller :
[HttpPost]
public ActionResult Create(DemoContent model)
{
if (model.Age > 55)
{
var file = model.ImageUrl;
return Json(new { success = true });
}
else
{
return Json(new { success = false,message="Invalid Data" });
}
}
现在,当我打开弹出窗口时,当我提交表单时,它也会与文件一起发送到 Controller 。但问题是,一旦服务器返回成功消息,弹出窗口就会在空白页面中显示该消息,而不是捕获它并刷新当前页面或显示消息。知道为什么会发生这种情况。
源文件链接:https://drive.google.com/open?id=1W3H3kFEpHJWfaf7_UnJI3O5I900GxyC7
最佳答案
可能你在 document.ready() 函数中编写了你的 javascripts 函数,这就是为什么它再次令人耳目一新。
关于javascript - 通过 Bootstrap 模态对话框结果重定向浏览器的 ASP.Net MVC 文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51403506/