您可以对 actionresult 进行 ajax 调用,并从中返回图像的名称,并在 ajax 调用成功时更改图像 或者您可以执行此操作,我已在我的项目中实现了使您的 HTML 表单像这样
@using (Html.BeginForm("ActionResult", "Controller", FormMethod.Post, new { @id = "ImgForm", @enctype = "multipart/form-data", name = "ImgForm", target = "UploadTarget" }))
{
}
将 iframe 作为表单的目标
<iframe id="UploadTarget" name="UploadTarget" onload="UploadImage_Complete();" style="position: absolute;
left: -999em; top: -999em;"></iframe>
您的上传控制
然后上传图片并在表单上显示
function UploadImage() {
$("#ImgForm").submit(); //form id
}
function UploadImage_Complete() {
try {
//Check to see if this is the first load of the iFrame
if (isFirstLoad == true) {
isFirstLoad = false;
return;
}
//Reset the image form so the file won't get uploaded again
document.getElementById("ImgForm").reset();
//Grab the content of the textarea we named jsonResult . This shold be loaded into
//the hidden iFrame.
var newImg = $.parseJSON($("#UploadTarget").contents().find("#jsonResult")[0].innerHTML);
if (newImg.IsValid) {
document.getElementById("dp").src = newImg.ImagePath;
document.getElementById('profile-pic').src = newImg.ThumbnailPath;
document.getElementById("change").style.display = "block";
}
// If there was an error, display it to the user
if (newImg.IsValid == false) {
alert(newImg.Message);
return;
}
}
catch (e) {
}
}
您的操作将如下所示
public WrappedJsonResult ChangeImage(HttpPostedFileBase file)
{
}
你的 WrappedJsonResult 类看起来像
public class WrappedJsonResult : JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Write("<html><body><textarea id=\"jsonResult\" name=\"jsonResult\">");
base.ExecuteResult(context);
context.HttpContext.Response.Write("</textarea></body></html>");
context.HttpContext.Response.ContentType = "text/html";
}
}