c# MVC3 ajax.beginform 上传文件不起作用 [英] c# MVC3 ajax.beginform to upload file not working

查看:21
本文介绍了c# MVC3 ajax.beginform 上传文件不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

After clicking the submit button. I am getting null in entity. Do anyone have a solution?

查看

    @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" />
    }

控制器

    [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 页面.

I have written a little hack. It works fine in most of browsers, but FormData object doesn't supported in IE. You could add this code to you custom js file or html page.

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);

这篇关于c# MVC3 ajax.beginform 上传文件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆