我遵循以下 url 中的示例,该示例显示了如何使用 jQuery Form 插件将异步文件上传到我的 .NET MVC 控制器。( http://aspzone.com/tech/jquery-file-upload-in-asp-net-mvc-without-using-flash/)第一次一切都很好,在我第一次上传文件后,我通过返回的 PartialView 替换了表单所在的 div。当 div 被替换时,我会调用一个 javascript 函数来重建 ajaxForm 对象,但这似乎是事情停止工作的地方。当代码第一次返回时,我得到替换的 div 就好了,并且外观正确,但是 javascript 代码似乎没有将 ajaxForm 对象附加到替换的 div 内存在的表单上。这意味着我第二次使用表单发布时,它会将用户重定向到页面之外。我想说这是控制器中的缓存问题,但我得到的响应显示了 ascx 中的更新项目列表。最后一件事,当我查看 IE 开发工具栏中的 dom 元素时,我看到一个类似于“jQuery16404440065521567182”的属性,其值为 33,并且在第一次提交后消失。我猜那是ajaxForm放在那里的。这是我正在使用的代码(更改了一些 javascript 命名空间以删除项目特定的命名):
ASCX 文件
<!-- Form to add a new record -->
<% using (Html.BeginForm("SaveAttachment", "Report", FormMethod.Post, new { enctype = "multipart/form-data", id = "AttachmentForm" })) { %>
<input type="hidden" name="ReportId" value="<%: Model.ReportId %>" />
<input type="file" name="FileUpload" value="" size="21" />
<label for="Title">
Title:</label>
<input type="text" name="Title" value="" />
<input type="submit" value="Add" class="inputButton" />
<% } %>
<!-- Display existing items -->
<% foreach (var item in Model.ExistingAttachments) { %>
<div>
<%: item.Sort %> <%: item.Title.PadRight(25, ' ').Substring(0, 25).TrimEnd() %></div>
<% } %>
ASPX 文件
<div id="AttachmentsWindow">
<% Html.RenderPartial("LoadAttachments", Model.ReportAttachments); %>
</div>
<!-- This form is used to refresh the above div -->
<% using (Ajax.BeginForm("LoadAttachments", new { ReportId = Model.ReportId },
new AjaxOptions {
HttpMethod = "Post",
LoadingElementId = "LoadingAttachments",
UpdateTargetId = "AttachmentsWindow",
InsertionMode = InsertionMode.Replace,
OnComplete = "Report.InitAttachment"
}, new { id = "LoadAttachmentsForm" })) { %>
<input type="submit" name="submit" value="" class="button" style="float:right;"
onmouseover="this.className='button buttonhov'" onmouseout="this.className='button'"/>
<% } %>
控制器
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public FileUploadJsonResult SaveAttachment(ReportAttachmentViewModel Attachment) {
if ( Attachment.FileUpload.ContentLength < 1 ){
return new FileUploadJsonResult { Data = new { message = "No file chosen." } };
}
var Report = this._reportRepository.GetById(Attachment.ReportId);
if (Report == null)
throw new Exception("Report not found");
MemoryStream target = new MemoryStream();
Attachment.FileUpload.InputStream.CopyTo(target);
byte[] data = target.ToArray();
ReportAttachment newobj = new ReportAttachment {
Attachment = data,
Description = string.Empty,
Name = Attachment.Title,
Report = Report,
ReportId = Report.Id
};
var result = this._reportAttachmentRepository.Add(ref newobj);
Report.ReportAttachments.Add(newobj);
ModelState.Clear();
if (!result.Success) {
StringBuilder sb = new StringBuilder();
foreach (var msg in result.Messages) {
sb.AppendLine(string.Format("{0}", msg.Message));
}
return new FileUploadJsonResult { Data = new { message = sb.ToString() } };
}
return new FileUploadJsonResult { Data = new { message = string.Format("{0} uploaded successfully.", System.IO.Path.GetFileName(Attachment.FileUpload.FileName)) } };
Javascript
//Report namespace
InitAttachment: function () {
jQuery('#AttachmentForm').ajaxForm({
iframe: true,
dataType: "json",
beforeSubmit: function () {
jQuery('#AttachmentForm').block({ message: 'Uploading File... ' });
},
success: function (result) {
jQuery('#AttachmentForm').unblock();
jQuery('#AttachmentForm').resetForm();
$.growlUI(null, result.message);
Editor.EndLoading(false, false, true);
},
error: function (xhr, textStatus, errorThrown) {
$("#ajaxUploadForm").unblock();
$("#ajaxUploadForm").resetForm();
$.growlUI(null, 'Error uploading file');
}
});
//Editor namespace
EndLoading: function (ReloadReportSections, ReloadReferences, ReloadAttachments) {
//Reload sections
if (ReloadReportSections)
jQuery('#LoadReportSectionsForm').submit();
if (ReloadReferences)
jQuery('#LoadReferencesForm').submit();
if (ReloadAttachments) {
jQuery('#LoadAttachmentsForm').submit();
}
//endReload
Report.InitAttachment();
//Close the loading dialog
jQuery('#LoadingWindow').dialog('close');
}