我有一个问题,我试图在提交表单后在同一页面上显示一条消息,但我的结果总是错误的,因为我在控制器中的操作被调用了两次,当我点击提交按钮时,第一次我的动作被称为数据通过正确的信息传递给动作并保存到数据库中,第二次每个参数都为空,因此返回假。
我想要一种只提交一次并在同一页面中返回适当的 Json 结果而不重定向的方法,我希望有人可以帮助我,这是我的代码:
我试过了:
function PdfHeaderAndFooterManager() {
$('#submitPdf').ajaxSubmit(function (e) {
$.ajax({
url: "/Dashboard/PdfHeaderAndFooterManager",
dataType: "json",
type:"POST",
data: {headerImage: headerImage, footerImage: footerImage},
success: function (data) {
if (data.success) {
alert(data.message);
$('#resultMessage').text(data.message).css("color", "RED");
}
else {
alert(data.message);
$('#resultMessage').text(data.message).css("color", "RED");
}
}
});
e.preventDefault();
});
}
我的观点为简单起见删除了一些代码
@using (Html.BeginForm("PdfHeaderAndFooterManager", "Dashboard", FormMethod.Post, new { enctype = "multipart/form-data", id = "formPdfImages" }))
div id="resultMessage"></div>
}
public ActionResult PdfHeaderAndFooterManager(HttpPostedFileBase headerImage, HttpPostedFileBase footerImage)
{
//some code to declare variables
if (headerImage != null)
{
if (!String.IsNullOrEmpty(headerImage.ContentType))
{
headerImageContentType = imageHelper.IsValidImageType(headerImage.ContentType);
if (headerImageContentType)
{
resizedHeaderImage = imageHelper.ResizeImage(headerImage.InputStream);
}
else
{
return Json(new { success = false, message = "Please Upload an image* file less than 2GB." });
}
}
}
if (footerImage != null)
{
if (!String.IsNullOrEmpty(footerImage.ContentType))
{
footerImageContentType = imageHelper.IsValidImageType(footerImage.ContentType);
if (footerImageContentType)
{
resizedFooterImage = imageHelper.ResizeImage(footerImage.InputStream);
}
else
{
return Json(new { success = false, message = "Please Upload an image* file less than 2GB." });
}
}
}
if (P24DataPrincipal.CurrentIdentity != null)
{
if (resizedHeaderImage != null || resizedFooterImage != null)
{
//add to DB code
return Json(new { success = true, message = "Image(s) Uploaded Successfully." });
}
else
{
return Json(new {success = false, message = "Upload atleast 1 image file." });
}
}
return Json("someview");
}
以上是我的操作,最重要的部分是“返回”关键字我只想看到,在我看来,即使结果为真,不仅结果为假,而且这个操作应该只调用一次而不是重定向。谢谢。