jQuery Form プラグインを使用して .NET MVC コントローラーに非同期ファイルをアップロードする方法を示す次の URL の例に従いました。( http://aspzone.com/tech/jquery-file-upload-in-asp-net-mvc-without-using-flash/)すべてが初めて完全にうまく機能し、最初にファイルをアップロードした後、フォームが返されたPartialViewを介して内部にあるdivを置き換えています。div が置き換えられると、javascript 関数を呼び出して ajaxForm オブジェクトを再構築しますが、動作が停止するようです。コードが最初に返されたときに、置き換えられた div を正常に取得し、外観は適切ですが、javascript コードは ajaxForm オブジェクトを置き換えられた div 内に存在するフォームに戻していないようです。これは、フォームを使用して 2 回目に投稿すると、ユーザーがページからリダイレクトされることを意味します。コントローラーのキャッシュの問題だと言いたいのですが、取得した応答には、ascx のアイテムの更新されたリストが表示されます。最後に一つだけ、IE 開発ツールバーの dom 要素を見ると、値が 33 の「jQuery16404440065521567182」のような属性が表示され、最初の送信後に消えます。私はそれが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');
}