Ebasse
Ebasse

Reputation: 143

image upload - MVC when used in bootstrap modal returns null

I'm binding the partial view inside the bootstrap modal popup. When I upload from the popup, the upload returning null. Instead if I open the partial View directly in browser, then the file is present in the model. So there is no problem with file upload. The problem is with modal popup or something.

It looks:

When posting from the modal popup, the content type is changed to application/x-www-form-urlencoded where as when using the partial view directly it is 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;
    });
}

I'm using AJAX posting to submit the data from my form. When using $(this).serialize() the ajax success is being called but the file is not returning as the content type is different. How can I change this??

Model

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

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

Please help to solve this.

Upvotes: 0

Views: 1157

Answers (1)

Garegin Hambardzumyan
Garegin Hambardzumyan

Reputation: 60

$(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;
    });
}

real working code

Upvotes: 2

Related Questions