javascript - 图像上传 - MVC 在 Bootstrap 模式中使用时返回 null

标签 javascript asp.net-mvc twitter-bootstrap file-upload

我正在将部分 View 绑定(bind)到 Bootstrap 模式弹出窗口内。当我从弹出窗口上传时,上传返回 null。相反,如果我直接在浏览器中打开部分 View ,则该文件将出现在模型中。所以文件上传是没有问题的。问题出在模态弹出窗口或其他东西上。

看起来:

从模式弹出窗口发布时,内容类型更改为 application/x-www-form-urlencoded,而直接使用部分 View 时,内容类型为 multipart/form-data。

modalform.js

$(function () {

    $.ajaxSetup({ cache: false });

    $("a[data-modal]").on("click", function (e) {

        // hide dropdown if any
        $(e.target).closest('.btn-group').children('.dropdown-toggle').dropdown('toggle');


        $('#myModalContent').load(this.href, function () {


            $('#myModal').modal({
                /*backdrop: 'static',*/
                keyboard: true
            }, 'show');

            bindForm(this);
        });

        return false;
    });


});

function bindForm(dialog) {

    $('form', dialog).submit(function () {
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {
                if (result.success) {
                    $('#myModal').modal('hide');
                    //Refresh
                    location.reload();
                } else {
                    $('#myModalContent').html(result);
                    bindForm();
                }
            }
        });
        return false;
    });
}

我正在使用 AJAX 发布来提交表单中的数据。当使用 $(this).serialize() 时,ajax 成功被调用,但由于内容类型不同,文件没有返回。我该如何改变这个?

型号

public partial class Produkty
    {
        public int PRO_Id { get; set; }
        public string PRO_Nazwa { get; set; }
        public string PRO_Jednostka { get; set; }
        public float PRO_Vat { get; set; }
        public string PRO_Rodzaj { get; set; }
        public string PRO_Opis { get; set; }
        public string PRO_Waluta { get; set; }
        public float PRO_CenaN { get; set; }
        public float PRO_CenaB { get; set; }
        public string PRO_ZdjecieN { get; set; }
        public byte[] PRO_ZdjecieF { get; set; }
    }

创建 View

@using (Html.BeginForm("Create", "Products", FormMethod.Post, new { enctype = "multipart/form-data" }))
//@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="modal-body">

        <div class="form-horizontal">
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            <div class="form-group">
                @Html.LabelFor(model => model.PRO_Nazwa, "Nazwa", htmlAttributes: new { @class = "control-label col-md-3" })
                <div class="col-md-9">
                    @Html.EditorFor(model => model.PRO_Nazwa, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.PRO_Nazwa, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.PRO_Jednostka, "Jednostka", htmlAttributes: new { @class = "control-label col-md-3" })
                <div class="col-md-9">
                    @Html.EditorFor(model => model.PRO_Jednostka, new { htmlAttributes = new { @class = "form-control", @Value = "szt." } })
                    @Html.ValidationMessageFor(model => model.PRO_Jednostka, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.PRO_Vat, "Vat", htmlAttributes: new { @class = "control-label col-md-3" })
                <div class="col-md-9">
                    @Html.DropDownListFor(model => model.PRO_Vat, new List<SelectListItem>
                    {
                        new SelectListItem{ Text = "23 %", Value = "23"},
                        new SelectListItem{ Text = "8 %", Value = "8" },
                        new SelectListItem{ Text = "5 %", Value = "5" },
                        new SelectListItem{ Text = "4 %", Value = "4" },
                        new SelectListItem{ Text = "0 %", Value = "0" }

                    }, "wybierz...", new { @class = "form-control", @id = "Value1" })
                    @Html.ValidationMessageFor(model => model.PRO_Vat, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.PRO_Rodzaj, "Rodzaj", htmlAttributes: new { @class = "control-label col-md-3" })
                <div class="col-md-9">
                    @Html.DropDownListFor(model => model.PRO_Rodzaj, new List<SelectListItem>
                    {
                        new SelectListItem{ Text = "towar", Value = "towar" },
                        new SelectListItem{ Text = "usługa", Value = "usługa" }

                    }, "wybierz...", new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.PRO_Rodzaj, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.PRO_Waluta, "Waluta", htmlAttributes: new { @class = "control-label col-md-3" })
                <div class="col-md-9">
                    @Html.DropDownListFor(model => model.PRO_Waluta, new List<SelectListItem>
                    {
                        new SelectListItem{ Text = "PLN", Value = "PLN" },
                        new SelectListItem{ Text = "EUR", Value = "EUR" },
                        new SelectListItem{ Text = "USD", Value = "USD" },
                        new SelectListItem{ Text = "GBP", Value = "GBP" },
                        new SelectListItem{ Text = "CHF", Value = "CHF" }

                    }, "wybierz...", new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.PRO_Waluta, "", new { @class = "text-danger" })
                </div>
            </div>


            <div class="form-group">
                @Html.LabelFor(model => model.PRO_CenaN, "Cena netto", htmlAttributes: new { @class = "control-label col-md-3" })
                <div class="col-md-9">
                    @Html.EditorFor(model => model.PRO_CenaN, new { htmlAttributes = new { @class = "form-control", @id = "Value2" } })
                    @Html.ValidationMessageFor(model => model.PRO_CenaN, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.PRO_CenaB, "Cena brutto", htmlAttributes: new { @class = "control-label col-md-3" })
                <div class="col-md-9">
                    @Html.EditorFor(model => model.PRO_CenaB, new { htmlAttributes = new { @class = "form-control", @id = "MultiplyValue1Value2" } })
                    @Html.ValidationMessageFor(model => model.PRO_CenaB, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.PRO_Opis, "Opis", htmlAttributes: new { @class = "control-label col-md-3" })
                <div class="col-md-9">
                    @Html.EditorFor(model => model.PRO_Opis, new { htmlAttributes = new { @class = "form-control", @Value = "brak" } })
                    @Html.ValidationMessageFor(model => model.PRO_Opis, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.PRO_ZdjecieF, "Plik", htmlAttributes: new { @class = "control-label col-md-3" })
                <div class="col-md-9">
                    <input type="file" id="file" class ="btn btn-default btn-file" name="file" />
                    @Html.ValidationMessageFor(model => model.PRO_ZdjecieF, "", new { @class = "text-danger" })
                </div>
            </div>

        </div>

    </div>

    <div class="modal-footer">
        <button class="btn" data-dismiss="modal">Anuluj</button>
        <input class="btn btn-primary" id="upload" type="submit" value="Zapisz" />
    </div>

Controller :

[HttpPost]
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Exclude = "PRO_ZdjecieF,PRO_Zdjecie")]Produkty pro, HttpPostedFileBase file)
        {           


            if (ModelState.IsValid)
            {
                //if (imageF != null)
                {
                    pro.PRO_ZdjecieF = new byte[file.ContentLength];
                    pro.PRO_ZdjecieN = file.ContentType;
                    file.InputStream.Read(pro.PRO_ZdjecieF, 0, file.ContentLength);
                }

                db.Produkties.Add(pro);
                db.SaveChanges();
                return Json(new { success = true });
            }

            return PartialView("Create", pro);
        }

请帮忙解决这个问题。

最佳答案

$(function () {

    $.ajaxSetup({ cache: false });

    $("a[data-modal]").on("click", function (e) {
        $("#myModalContent").load(this.href, function () {
            

            $("#myModal").modal({
                keyboard: true
            }, "show");

            bindForm(this);
        });

        return false;
    });
});

function bindForm(dialog) {
    
    $("#crtForm", dialog).submit(function () {
        var myform = document.getElementById("crtForm");
        var fdata = new FormData(myform);
       $.ajax({
            url: this.action,
            data: fdata,
            cache: false,
            processData: false,
            contentType: false,
            type: "POST",
            success: function (result) {
                if (result.success) {
                    $("#myModal").modal("hide");
                    location.reload();
                } else {
                    $("#myModalContent").html(result);
                    bindForm();
                }
            }
        });
        return false;
    });
}

实际工作代码

关于javascript - 图像上传 - MVC 在 Bootstrap 模式中使用时返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36690483/

相关文章:

c# - 如何在使用 AddNewtonsoftJson 时在 asp net core 3.1 mvc 中通过 DI(服务集合)检索 json 序列化程序设置

jquery - 如何用iframe分割页面

javascript - Cylcle2 没有循环寻呼机出现

javascript - Codesandbox 上的意外 token ReactJS 应用程序

javascript - 识别鼠标悬停在 onmouseover 函数中的元素

javascript - 为什么我的带功能箭头的 map() 不起作用?

c# - 处理多项操作的最佳方式是什么?

c# - 不支持关键字 : 'data source' . - Azure

css - 具有固定大小和滚动条的 Bootstrap 缩略图

javascript - 只能使用 jQuery 一次更改文本的字体系列