0

我遵循以下 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 %>&nbsp;<%: 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');
}
4

2 回答 2

0

您可能希望在调用之前删除隐藏的iframe(如果存在)。听起来文件上传表单的目标可能会搞砸,如果之前上传的目标仍然存在。我在 中遇到过类似的问题,但不能说是一样的。InitAttachment()ajaxForm()iframeExtJS

于 2011-11-17T04:15:06.183 回答
0

原来是我在错误的位置调用更新。在我看来,我会想象它OnSuccess会在之前触发OnComplete,但在 MS Ajax 模型中它不会。 OnSuccess正在被调用,看起来它正在影响代码,因为它正在命中我设置的所有断点,但它一定是在调用 Replace 逻辑之前命中了旧的 DOM 元素。我似乎找不到任何有关这种情况发生顺序的文档,但我注意到当我.ajaxForm从该AjaxOptions.OnSuccess属性调用时,一切正常。所以我的建议简而言之:

使用AjaxOptions.OnSuccessandAjaxOptions.OnFailed来影响更新的 DOM,但AjaxOptions.OnComplete如果您需要临时逻辑。

于 2011-11-19T03:35:05.253 回答