0

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.

Ebasse
  • 143
  • 13
  • Your need to use `FormData` to post a file using ajax - refer [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681) –  Apr 18 '16 at 09:47
  • And why do you have `location.reload();` in the success callback. The whole point of ajax is to stay on the same page so there is no point using ajax if your then going to refresh the page. –  Apr 18 '16 at 09:54
  • I open my website on for example on: localhost:9999/Product/Index When I click Create icon that displays a modal popup with page /Product/Crate When i click save, this popup should close and reload site /Product/Index. – Ebasse Apr 18 '16 at 10:00
  • Its pointless to use ajax if you just going to reload the page. You may as weel do a normal submit and redirect back the `Index()` method –  Apr 18 '16 at 10:10
  • But I would like to popup a closed (just like it's been until now) and refreshed index page. How can I do it? – Ebasse Apr 18 '16 at 10:26

1 Answers1

2

$(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