HttpPostedFileBase always empty when passing csv to the controller

1

Good Afternoon Personal,

I'm having trouble passing a csv that is being sent from ajax using jquery to the controller where it always arrives null.

Could you help me?

View:

@using (Html.BeginForm("Importar", "Contatos", FormMethod.Post, new { enctype = "multipart/form-data",id="formUpload" }))
{

    <div class="modal fade" id="importarCSV">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="modal-title"> <i class="icon-user"></i> Importar CSV</h4>
                </div>
                <div class="modal-body row">
                    <div class="col-lg-12">

                        @Html.TextBox("arquivoExcel", "", new { type = "file", required = "required" })

                    </div>

                    <div class="col-lg-12">
                        <br />
                        @Html.Label("O que deseja fazer com os contatos deste arquivo ?", null, new { @class = "lead" })

                        <br />
                        <div class="form-group">


                            @Html.RadioButton("0", "", new { id = "vinculaAtualizaG", required = "required" })
                            <small>Vincular e atualizar um grupo</small>





                            <br />
                            @Html.RadioButton("0", "", new { id = "vinculaNaoAtualizaC", required = "required" })

                            <small>Vincular a um grupo, sem atualizar os dados dos contatos</small>
                            <br />
                            @Html.RadioButton("0", "", new { id = "vinculaNovoGr", required = "required" })

                            <small>Vincular a um novo grupo, sem atualizar os dados dos contatos</small>
                        </div>

                        @Html.DropDownList("grupos", (List<SelectListItem>)ViewBag.Grupos, new { @class = "form-control" })
                        @Html.TextBox("grupooo", null, new { @class = "form-control text-box single-line" })

                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-warning " id="dados">Importar</button>

                </div>

            </div>

        </div>
    </div>


}

Jquery:

$('#dados').on('click', function () {
    var txtGrupo;
    var option;
    var radioSelected;

    var radios = document.getElementsByName("0");
    for (var i = 0; i < radios.length; i++) {

        if (radios[i].checked) {
            var id = $(radios[i]).attr("id");


            radioSelected = id;


            if (id == "vinculaNovoGr") {
                txtGrupo = $("#grupooo").val();
            } else {
                option = $('#grupos').find(":selected").text();
            }

        }
    }
    var formData = new FormData($('#formUpload')[0]);
    debugger;


    $.ajax({
        url: "/Contatos/Importar",
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: JSON.stringify({


            grupooo: $("#grupooo").val(),
            id: radioSelected,
            opcaoCombo: $('#grupos').find(":selected").text(), //,
             arquivoExcel: formData


        }),
        async: false
    });


});

CONTROLLER:

    [HttpPost]
    public ActionResult Importar(HttpPostedFileBase arquivoExcel,string teste, string id, string grupooo, string opcaoCombo)
    {


        var d = HttpContext.Request.Files[0]; 
        var r = id;
        var opc = grupooo;
        var fs = opcaoCombo;

        return RedirectToAction("Index", "Contatos");
    }

    
asked by anonymous 24.06.2018 / 20:12

1 answer

0

Get the form data:

var formData = new FormData($('#formUpload')[0]);

Set the Date property of the Ajax function like this:

data: formData

Here is an example of a file post with Ajax and ProgressBar:

<div class="progress">
    <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="min-width: 2em;">
        0%
    </div>
</div>

<div id="divProgresso"></div>

<form id="frmEnviar" action="~/enviar")" method="post" enctype="multipart/form-data">
    <input type="file" name="arquivo" />
    <input type="file" name="arquivo2" />
    <button>Enviar</button>
    <input type="reset" />
</form>

<script>
    $("#frmEnviar").submit(function (e) {
        var form = $(e.target);
        data = new FormData(form[0]);//IE10+

        $.ajax({
            url: form.attr("action"),
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            success: function (data) {
                alert(data);
            },
            xhr: function () {
                var jqXHR = new window.XMLHttpRequest();
                //Upload progress
                jqXHR.upload.addEventListener("progress", function (evt) {
                    if (evt.lengthComputable) {
                        var percentComplete = Math.floor((evt.loaded / evt.total) * 100);
                        //Do something with upload progress
                        $("#divProgresso").html("Upload: " + percentComplete + "%");

                        $('.progress-bar').css('width', percentComplete + '%').attr('aria-valuenow', percentComplete).text(percentComplete + '%');
                    }
                }, false);
                //Download progress
                jqXHR.addEventListener("progress", function (evt) {
                    if (evt.lengthComputable) {
                        var percentComplete = Math.floor((evt.loaded / evt.total) * 100);
                        //Do something with download progress
                        $("#divProgresso").html("Download: " + percentComplete + "%");

                        $('.progress-bar').css('width', percentComplete + '%').attr('aria-valuenow', percentComplete).text(percentComplete + '%');
                    }
                }, false);

                return jqXHR;
            }
        });

        return false;
    });
</script>
    
28.06.2018 / 22:22