我正在尝试为我正在开发的网络应用程序设置一个简单的文件/图像上传。为了提供帮助,我正在使用此处找到的 jquery 表单插件:http: //jquery.malsup.com/form/
从示例中,您似乎可以通过定义“目标”属性来定义希望将返回数据放置在何处。
所以问题是,我的整个浏览器不是在定义的“目标”位置内渲染部分,而是“回发”,我被重定向到单个部分页面。
public PartialViewResult BackgroundImageWindow()
{
return PartialView();
}
背景图像窗口.cshtml
<div class="divBGImageLoader">
<form id="FileUploadForm" action='@Url.Action("FileUpload", "SlideShow")' method="POST" enctype="multipart/form-data">
<input type="file" name="file" />
<input id="UploadFileButton" type="submit" value="Upload" />
</form>
<div id="BGImageTable">
@{Html.RenderAction("BackgroundImageWindowTable");}
</div>
</div>
这里是:
public PartialViewResult BackgroundImageWindowTable()
{
DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/Content/uploads"));
List<FileInfo> files = di.GetFiles().ToList();
return PartialView(files); // returns a partial with a table of the uploaded files
}
javascript:
$("#UploadFileButton").live("submit", function(e){
e.preventDefault(); // <- doc file said it needed this
e.stopImmediatePropagation(); // <- uuh just in case
var ajaxSubmitOptions = {
target: $("#BGImageTable"),
beforeSubmit: function () {
//$("#loading").show();
},
success: function (data) {
//$("#loading").hide();
}
};
$(this).ajaxSubmit(ajaxSubmitOptions);
return false; //<- documentation said this was necessary to stop the 'post back'
});
文件上传部分:
public ActionResult FileUpload(HttpPostedFileBase file)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(file.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/Content/uploads"), fileName);
file.SaveAs(path);
}
// redirect back to the index action to show the form once again
return RedirectToAction("BackgroundImageWindowTable");
}
所以就像我之前说的,这似乎是有效的,除了部分被渲染和显示的事实,就像它是一个单独的页面一样。