asp.net - c# MVC3 ajax.beginform 上传文件不工作

标签 asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

点击提交按钮后。我在实体中变得空了。 有人有解决方案吗?

查看

    @using (Ajax.BeginForm("CreateRoom", "Room", new AjaxOptions { HttpMethod = "POST", OnComplete = "window.location.href='Index'" }, new { enctype = "multipart/form-data", id = "ajaxUploadForm" }))
    {
        <input type="file" name="Room" />
        <input type="submit" value="OK" />
    }

Controller

    [HttpPost]
    public ActionResult CreateRoom(RoomFileView entity)
    {
        //code
    }

模型

     public class RoomFileView
    {
        public RoomFileView();

        public int BuildingId { get; set; }
        public int CityId { get; set; }
        public int CountryId { get; set; }
        public int FloorId { get; set; }
        public int LocationId { get; set; }
        public HttpPostedFileWrapper Room { get; set; }

        public string Content();
    }

最佳答案

我写了一个小技巧。它在大多数浏览器中都可以正常工作,但 IE 不支持 FormData 对象。您可以将此代码添加到您的自定义 js 文件或 html 页面。

window.addEventListener("submit", function (e) {
    var form = e.target;
    if (form.getAttribute("enctype") === "multipart/form-data") {
        if (form.dataset.ajax) {
            e.preventDefault();
            e.stopImmediatePropagation();
            var xhr = new XMLHttpRequest();
            xhr.open(form.method, form.action);
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    if (form.dataset.ajaxUpdate) {
                        var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
                        if (updateTarget) {
                            updateTarget.innerHTML = xhr.responseText;
                        } 
                    }
                }
            };
            xhr.send(new FormData(form));
        }
    }
}, true);

关于asp.net - c# MVC3 ajax.beginform 上传文件不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14972470/

相关文章:

asp.net-mvc - 如何将 MVC 模型类与现有数据库表和架构相匹配

asp.net - 如何在 ASP.NET 3.5 中对每个 http 请求进行缓存

c# - NLog 自定义 LayoutRenderer - json : can't get working

android - 将 ASP.NET 网站转换为 native Android/iOS 应用程序

c# - MVC 内容文件夹问题 - 未找到 Twitter Bootstrap 样式表

c# - 使用 Entity Framework 时了解对象

c# - 使用 CaSTLe windsor 创建对象而不是工厂类

c# - 在 MVC3 应用程序中为异步处理程序保留依赖注入(inject)对象

c# - 当从 javascript 调用操作时,Asp.net MVC Controller 参数为 null

asp.net - 在 Page_Load 之前处理事件