Asp.net mvc 2 jQuery ajax表单文件上载到.Net MVC,使用InsertionMode。仅替换一次

Asp.net mvc 2 jQuery ajax表单文件上载到.Net MVC,使用InsertionMode。仅替换一次,asp.net-mvc-2,file-upload,jquery-forms-plugin,Asp.net Mvc 2,File Upload,Jquery Forms Plugin,我遵循了下面url中的一个示例,该示例演示了如何使用jQuery表单插件将异步文件上载到我的.NET MVC控制器。()第一次一切都非常好,在我第一次上传文件之后,我通过返回的PartialView替换了表单所在的div。当div被替换时,我会调用一个javascript函数来重建ajaxForm对象,但这似乎是停止工作的地方。当代码第一次返回被替换的div时,我感觉很好,外观也很好,但是javascript代码似乎没有将ajaxForm对象附加回被替换div中的表单。这意味着第二次发布表单时,

我遵循了下面url中的一个示例,该示例演示了如何使用jQuery表单插件将异步文件上载到我的.NET MVC控制器。()第一次一切都非常好,在我第一次上传文件之后,我通过返回的PartialView替换了表单所在的div。当div被替换时,我会调用一个javascript函数来重建ajaxForm对象,但这似乎是停止工作的地方。当代码第一次返回被替换的div时,我感觉很好,外观也很好,但是javascript代码似乎没有将ajaxForm对象附加回被替换div中的表单。这意味着第二次发布表单时,它会将用户重定向到页面之外。我想说这是控制器中的缓存问题,但是我得到的响应显示了ascx中更新的项目列表。最后一件事,当我在IE开发工具条中查看dom元素时,我看到一个类似“jQuery1644440065521567182”的属性,其值为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 %>&nbsp;<%: item.Title.PadRight(25, ' ').Substring(0, 25).TrimEnd() %></div>
<% } %>

在调用
ajaxForm()
之前,您可能需要删除
InitAttachment()中隐藏的
iframe
(如果存在)。 如果先前上传的
iframe
仍然存在,那么文件上传表单的目标可能会变得混乱。
我在
ExtJS
中遇到过类似的问题,但不能说是同一个问题。

结果是我在错误的位置调用了更新。在我看来,我可以想象,
OnSuccess
会在
OnComplete
之前启动,但在MS-Ajax模型中它不会
OnSuccess
正在被调用,它似乎正在影响代码,因为它正在命中我设置的所有断点,但它必须在调用替换逻辑之前命中旧的DOM元素。我似乎找不到任何文档讨论这种情况发生的顺序,但我注意到,当我从
AjaxOptions.OnSuccess
属性调用
.ajaxForm
时,一切都运行良好。总之,我的建议是:

如果需要临时逻辑,请使用
AjaxOptions.OnSuccess
AjaxOptions.OnFailed
影响更新的DOM,但
AjaxOptions.OnComplete

<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)) } };
//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');
}