使用 MVC 从标准 Html 表单回发部分视图

发布于 2024-09-05 22:08:42 字数 340 浏览 3 评论 0原文

我的 MVC 视图上有一个文件上传按钮。文件上传后,页面上的 FileList 部分视图应该刷新。

我尝试使用Ajax.BeginForm()上传,但发现Ajax不会提交文件数据。

我现在可以使用 jQuery Form 插件 进行文件上传,该插件允许您使用 ajax 化普通的 Html.BeginForm() 提交方法。

使用此方法是否仍然可以触发部分页面更新?

I have a file upload button on my MVC view. After the file is uploaded, my FileList partial view on the page should refresh.

I tried to upload with Ajax.BeginForm(), but have discovered that Ajax will not submit file data.

I've got the file upload working now by using the jQuery Form plugin, which lets you ajaxify the normal Html.BeginForm() submit method.

Is is still possible to trigger the partial page update using this method?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

[浮城] 2024-09-12 22:08:42

是的,您可以使用 .ajaxForm 中的 success 选项从文件上传传回数据,然后将该数据传递到 PartialView 或仅刷新部分。

     // Setup the from plugin
    $('#formId').ajaxForm(
                          success: function(data) { UploadSuccess(data); },
                          dataType: 'json', 
                          iframe:true);
    $('#formId').submit();

    // Success callback fundtion
    function UploadSuccess(data)
    {
        // You can then access any data in the JSON object and pass it in the route to the partial
        $('#divId').load('/FileList/' + data.FileName);
    }

// Original HTML of partial
<div id="divId">
    <%Html.RenderPartial("FileList");%>
</div>

        // Action to handle upload
        public FileUploadJSONResult Upload()
        {
            FileUploadJSONResult result;

            try
            {
                if (Request.Files.Count > 0)
                {
                    //  Logic to save file goes here

                    result = new FileUploadJSONResult()
                    {
                        Data = new
                        {
                            FileName = "Test filename",
                            ErrorMessage = string.Empty
                        }
                    };
                }
                else
                {
                    result = new FileUploadJSONResult
                    {
                        Data = new
                        {
                            FileName = string.Empty,
                            LogicalName = string.Empty,
                            ErrorMessage = "No file to upload. Please select a file to upload."
                        }
                    };
                }
            }
            catch (Exception e)
            {
                Exception root = e;
                while ((root.InnerException) != null)
                {
                    root = root.InnerException;
                }

                result = new FileUploadJSONResult
                {
                    Data = new
                    {
                        FileName = string.Empty,
                        LogicalName = string.Empty,
                        ErrorMessage = root.Message
                    }
                };
            }

            return result;
        }

// Then needed to wrap the JSON result due to the iframe textarea issue with this plugin
public class FileUploadJSONResult : JsonResult
    {  
        /// <summary>
        /// The following explanation of this code is from http://www.malsup.com/jquery/form:
        /// 
        ///  Since it is not possible to upload files using the browser's XMLHttpRequest object, the Form Plugin 
        ///  uses a hidden iframe element to help with the task. This is a common technique, but it has inherent limitations. 
        ///  The iframe element is used as the target of the form's submit operation which means that the server response is 
        ///  written to the iframe. This is fine if the response type is HTML or XML, but doesn't work as well if the 
        ///  response type is script or JSON, both of which often contain characters that need to be repesented using 
        ///  entity references when found in HTML markup.
        ///  To account for the challenges of script and JSON responses, the Form Plugin allows these responses to be 
        ///  embedded in a textarea element and it is recommended that you do so for these response types when used in 
        ///  conjuction with file uploads. Please note, however, that if a file has not been selected by the user for the 
        ///  file input then the request uses normal XHR to submit the form (not an iframe). This puts the burden on your 
        ///  server code to know when to use a textarea and when not to. If you like, you can use the iframe option of the 
        ///  plugin to force it to always use an iframe mode and then your server can always embed the response in a textarea. 
        /// </summary>
        /// <param name="context">Controller context</param>
        public override void ExecuteResult(ControllerContext context)
        {
            this.ContentType = "text/html";
            context.HttpContext.Response.Write("<textarea>");
            base.ExecuteResult(context);
            context.HttpContext.Response.Write("</textarea>");
        }
    }

Yeah you could use the success option in the .ajaxForm to pass back data from the file upload and then pass that data to the PartialView or just refresh the partial.

     // Setup the from plugin
    $('#formId').ajaxForm(
                          success: function(data) { UploadSuccess(data); },
                          dataType: 'json', 
                          iframe:true);
    $('#formId').submit();

    // Success callback fundtion
    function UploadSuccess(data)
    {
        // You can then access any data in the JSON object and pass it in the route to the partial
        $('#divId').load('/FileList/' + data.FileName);
    }

// Original HTML of partial
<div id="divId">
    <%Html.RenderPartial("FileList");%>
</div>

        // Action to handle upload
        public FileUploadJSONResult Upload()
        {
            FileUploadJSONResult result;

            try
            {
                if (Request.Files.Count > 0)
                {
                    //  Logic to save file goes here

                    result = new FileUploadJSONResult()
                    {
                        Data = new
                        {
                            FileName = "Test filename",
                            ErrorMessage = string.Empty
                        }
                    };
                }
                else
                {
                    result = new FileUploadJSONResult
                    {
                        Data = new
                        {
                            FileName = string.Empty,
                            LogicalName = string.Empty,
                            ErrorMessage = "No file to upload. Please select a file to upload."
                        }
                    };
                }
            }
            catch (Exception e)
            {
                Exception root = e;
                while ((root.InnerException) != null)
                {
                    root = root.InnerException;
                }

                result = new FileUploadJSONResult
                {
                    Data = new
                    {
                        FileName = string.Empty,
                        LogicalName = string.Empty,
                        ErrorMessage = root.Message
                    }
                };
            }

            return result;
        }

// Then needed to wrap the JSON result due to the iframe textarea issue with this plugin
public class FileUploadJSONResult : JsonResult
    {  
        /// <summary>
        /// The following explanation of this code is from http://www.malsup.com/jquery/form:
        /// 
        ///  Since it is not possible to upload files using the browser's XMLHttpRequest object, the Form Plugin 
        ///  uses a hidden iframe element to help with the task. This is a common technique, but it has inherent limitations. 
        ///  The iframe element is used as the target of the form's submit operation which means that the server response is 
        ///  written to the iframe. This is fine if the response type is HTML or XML, but doesn't work as well if the 
        ///  response type is script or JSON, both of which often contain characters that need to be repesented using 
        ///  entity references when found in HTML markup.
        ///  To account for the challenges of script and JSON responses, the Form Plugin allows these responses to be 
        ///  embedded in a textarea element and it is recommended that you do so for these response types when used in 
        ///  conjuction with file uploads. Please note, however, that if a file has not been selected by the user for the 
        ///  file input then the request uses normal XHR to submit the form (not an iframe). This puts the burden on your 
        ///  server code to know when to use a textarea and when not to. If you like, you can use the iframe option of the 
        ///  plugin to force it to always use an iframe mode and then your server can always embed the response in a textarea. 
        /// </summary>
        /// <param name="context">Controller context</param>
        public override void ExecuteResult(ControllerContext context)
        {
            this.ContentType = "text/html";
            context.HttpContext.Response.Write("<textarea>");
            base.ExecuteResult(context);
            context.HttpContext.Response.Write("</textarea>");
        }
    }
谷夏 2024-09-12 22:08:42

如果我正确理解您的问题,您应该能够为 jQuery Form 插件的 success 属性提供回调函数(查看此链接以了解所有选项:http://jquery.malsup.com/form/#options-object)。

然后,在该 javascript 函数内,您可以对 FileList 部分视图进行任何需要的更新...无论是更新部分视图的 GET 请求,还是仅捕获responseText< /code> 来自 jQuery Form 插件的成功回调函数。

If I'm understanding your question correctly, you should be able to provide a callback function to the success property of the jQuery Form plugin (check out this link for all of the options: http://jquery.malsup.com/form/#options-object).

Then inside that javascript function you can do whatever updates to the FileList partial view that you need to... whether that be a GET request to update the partial view, or just capturing the responseText from the success callback function of the jQuery Form plugin.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文