locked
Two imput buttons, how can i send them to the controller as an array? RRS feed

  • Question

  • User210306721 posted

    I have two Imputs, they only accept one file. 

    I want to add them into an Array in javascript but im not sure how to use razor and save it into my model?

    I used before httpContenFilebase but that works with only one file. 

    @model Contents.Models.NotificationViewModel
    @using Web.FrontEnd.Models;
    @using Web.FrontEnd.Helpers;
    
    @{
        Layout = "~/Views/Shared/_Default.cshtml";
    }
    
    <style>
        #NotificationTest {
            margin: 0 auto;
            width: 600px;
        }
    
        #control1[disabled] {
            background: transparent;
        }
    
        #control2[disabled] {
            background: transparent;
        }
    </style>
    
    <div class="justify-content-center" id="NotificationTest">
        <div class="col-12">
    
            @using (Html.BeginForm("Save", "Notification", FormMethod.Post, new { model = @Model, @class = "form-horizontal" }))
            {
                    <label>Asunto:</label><br />
                    @Html.InputFormFor(m => m.notification.Subject)
                    <label>Título:</label><br />
                    @Html.InputFormFor(m => m.notification.Title)
                    <label>Sub Título:</label><br />
                    @Html.InputFormFor(m => m.notification.SubTitle)
                    <label>Descripción:</label><br />
                    @Html.TextAreaFor(m => m.notification.MainText, new { })<br />
    
                    <label>Elegir imagen de vista previa:</label><br />
    
                    <input type="button" value="Eliminar Archivo" id="clear1" class="clear" style="color:black; float: left;" onclick="obj=document.getElementById('control1');obj.value='';obj.disabled=false">
                    <input type="file" name="UploadFile1" id="control1" class="UploadFile1" style="float: left;" onchange="this.disabled=true;">
                    <br />
                    <br />
                    <label>Elegir imagen de contenido:</label>
                    <br />
                    <input type="button" value="Eliminar Archivo" id="clear2" class="clear" style="color:black; float: left;" onclick="obj=document.getElementById('control2');obj.value='';obj.disabled=false">
                    <input type="file" name="UploadFile2" id="control2" class="UploadFile2" style="float: left;" onchange="this.disabled=true;">
                    <br />
                    <br />
                    <label>Enviar a:</label><br />
    
                    for (int i = 0; i < Model.SeleccionTipos.Count; i++)
                    {
    
                        @Html.HiddenFor(m => m.SeleccionTipos[i].Value);
                        @Html.HiddenFor(m => m.SeleccionTipos[i].Text);
    
                        <label>@Html.CheckBoxFor(m => m.SeleccionTipos[i].Selected, new { @class = "chk", id = "Tipos" })&nbsp;@Model.SeleccionTipos[i].Text</label>
                        <br />
                    }
                    <br />
    
                    @Html.HiddenFor(m => m.ImageGuid)
    
                    @Html.CrudSumbitForm()
             }
        </div>
    </div>
    <script type="text/javascript">
    
        //-----------LOGICA-BOTON-1-----------//
    
        $("#clear1").hide();
    
        var UploadFile1 = $("#control1"),
            clearBn1 = $("#clear1");
    
        clearBn1.on("click", function () {
            UploadFile1.replaceWith(UploadFile1.val(''));
        });
    
        $('#clear1').on('click', function (e) {
            $("#clear1").hide();
        });
    
        //-----------LOGICA-BOTON-2-----------//
    
        $("#clear2").hide();
    
        var UploadFile2 = $("#control2"),
            clearBn2 = $("#clear2");
    
        clearBn2.on("click", function () {
            UploadFile2.replaceWith(UploadFile2.val(''));
        });
    
        $('#clear2').on('click', function (e) {
            $("#clear2").hide();
        });
    
        //-----------LOGICA-CHECKBOX-----------//
    
        $('input.chk').on('change', function (ev) {
            ev.preventDefault()
    
            if ($(this).prop('checked')) {
                $('input.chk').not($(this)).prop('checked', false)
            }
    
            if (1 > $('input.chk:checked').length) {
                $(this).prop('checked', true)
            }
            return false;
        });
    
        //-----------LOGICA-SUBIR-ARCHIVO1?????-------//
    
    
        $('.UploadFile1').on('change', function (e) {
            $("#clear1").show();
            var files = e.target.files;
            if (files.length > 0)
            {
                //if (window.FormData !== undefined) {
    
                //    var data = new FormData();
                //    for (var x = 0; x < files.length; x++)
                //    {
                //        data.append("file" + x, files[x]);
                //    }
    
                //    //LOGICA ENVIO AL CONTROLADOR
    
                //    $.ajax({
                //        type: "POST",
                //        url: '/Notification/UploadFile/',
                //        contentType: false,
                //        processData: false,
                //        data: data
                //    });
                //}
                //else
                //{
                //    alert("This browser doesn't support HTML5 file uploads!");
                //}
            }
        });
    
        //-----------LOGICA-SUBIR-ARCHIVO2?????-------//
    
        $('.UploadFile2').on('change', function (e) {
            $("#clear2").show();
            var files = e.target.files;
            if (files.length > 0) {
                //if (window.FormData !== undefined) {
                //    var data = new FormData();
                //    for (var x = 0; x < files.length; x++) {
                //        data.append("file" + x, files[x]);
                //    }
    
                //    //LOGICA ENVIO AL CONTROLADOR
    
                //    $.ajax({
                //        type: "POST",
                //        url: '/Notification/UploadFile/',
                //        contentType: false,
                //        processData: false,
                //        data: data
                //    });
                //}
                //else {
                //    alert("This browser doesn't support HTML5 file uploads!");
                //}
            }
        });
    </script>
    <script src="https://cdn.tiny.cloud/1/qagffr3pkuv17a8on1afax661irst1hbr4e6tbv888sz91jc/tinymce/5/tinymce.min.js"></script>
    <script type="text/javascript">
    
        $(document).ready(function () {
            tinymce.init({
                selector: 'textarea',
                height: 500,
    
                plugins: [
                    'advlist autolink lists link image charmap print preview anchor',
                    'searchreplace visualblocks code fullscreen',
                    'insertdatetime media table paste code help wordcount'
                ],
    
                toolbar: ' bold italic underline forecolor backcolor removeformat outdent indent aligncenter alignjustify alignleft alignnone alignright copy cut paste fontselect fontsizeselect  undo redo remove formatpainter fullpage hr fliph flipv rotateleft rotateright insertdatetime bullist numlist media nonbreaking pagebreak pageembed permanentpen quickimage quicklink quicktable restoredraft cancel save spellchecker visualchars ',
    
                content_css: [
                    '//fonts.googleapis.com/css?family=Lato:300,300i,400,400i',
                    '//www.tiny.cloud/css/codepen.min.css'
                ]
            });
        });
    </script>
    

     

    Tuesday, April 14, 2020 1:56 PM

Answers

  • User475983607 posted

    Look, maybe your are tired, and maybe i look as an ignorant, but im doing exactly that and does not working. (files are in null on the Model) 

    My sample code functions as expected.  Your code disables the file inputs.  Browsers do not submit disabled fields.  Once I remove the onchange event the files upload as expected.

    <form method="post" enctype="multipart/form-data">
        <div>
            <input id="Message" type="text" name="Message" value="Hello World" />
        </div>
    
        <input type="button"
               value="Eliminar Archivo"
               id="clear1" class="clear"
               style="color:black; float: left;"
               onclick="obj=document.getElementById('control1');obj.value='';obj.disabled=false">
        <input type="file" name="files" id="control1" class="UploadFile1" style="float: left;">
        <br />
        <br />
        <label>Elegir imagen de contenido:</label>
        <br />
        <input type="button"
               value="Eliminar Archivo"
               id="clear2" class="clear"
               style="color:black; float: left;"
               onclick="obj=document.getElementById('control2');obj.value='';obj.disabled=false">
        <input type="file" name="files" id="control2" class="UploadFile2" style="float: left;">
        <br />
        <br />
        <div>
            <input id="Submit1" type="submit" value="submit" />
        </div>
    </form>



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, April 15, 2020 2:07 PM

All replies

  • User210306721 posted

    I declared a global Array like this: 

    var FileArray = []

    And on 

    LOGICA-SUBIR-ARCHIVO (1 and 2)

    I push the files value.

    So that would be my Array of files.

    Tuesday, April 14, 2020 2:12 PM
  • User475983607 posted

    I used before httpContenFilebase but that works with only one file. 

    Use an collection.

    IEnumerable<HttpPostedFileBase> files

    Tuesday, April 14, 2020 2:16 PM
  • User210306721 posted

    I Added 

    public IEnumerable<HttpPostedFileBase> Files { get; set; }

    and i think i should use some hidden razor:

    @Html.HiddenFor(m => m.Files, new { @id = "Files" });

    and i should assign value like this?...

    document.getElementById('Files').value = files;

    Could you give an example? 

    Tuesday, April 14, 2020 3:15 PM
  • User475983607 posted

    I Added 

    public IEnumerable<HttpPostedFileBase> Files { get; set; }

    and i think i should use some hidden razor:

    @Html.HiddenFor(m => m.Files, new { @id = "Files" });

    and i should assign value like this?...

    document.getElementById('Files').value = files;

    Could you give an example? 

    I have no idea what you're asking.

    This HttpPostedFileBase type is used on the server to read files streams uploaded from a client.  In a browser based application, the file stream comes from either a form post using a file input or the FormData object when using JavaScript to upload files.

    A hidden field is a is not a stream.  I don't understand the significance of the hidden fields in your design. 

    There are plenty of examples that upload files in MVC and I'm positive we've been down this road in your other threads.  The following link shows how to use FormData to upload files.

    https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

    Tuesday, April 14, 2020 3:39 PM
  • User210306721 posted

    Thanks but that good examples work with PHP. (And we dont) 

    My form has a submit logic (Hidden in somewhere else, cant be accessed or changed) All i know that when submit form button is clicked

    "Save" Action controller will be triggered.  Also by Javascript i could be able to use this on submit.

    My idea was to create a Hidden razor access to the "public IEnumerable<HttpPostedFileBase> Files { get; set; }" on the fron end and save the files from javascript into that variable.

    if the files could be there im pretty sure that when save is triggered i will be hable to handle that variable using a foreach file in Files... do something inside the model. 

    Thats why all the traditional common people uses some formdata, calls another metod, or use other thechnics wich is fine. But this is the page where i have to work (not mine , whit their rules). 

    Tuesday, April 14, 2020 5:40 PM
  • User-474980206 posted

    you are totally confused. please read a MVC file upload tutorial. it works just php other than different binding name conventions.

    a form post with files is a multi-part form post. the post data looks like a standard mime message with each form field and file its own mime-part.  on binding MVC adds mime-type files to file collection (Request.Files) and mime-type form fields to the forms collection (Request.Form). these collections are then bound to the action parameters. if you named all the <input type="file" name="Files"> then they will all bind to a model parameter named "Files".

    client side you control the form post of files by creating / removing <input type=file>. you can not set the filename, the user must do that via the browser file picker. you can change the name attribute, or disable or clear name the control if you don't want it included in the post.

     if you are using ajax, you can use the FormData() but, again, the user must select the file name via the dialog.

    Tuesday, April 14, 2020 6:11 PM
  • User210306721 posted

    I didnt understand a word of what you say about mimes, but i believe you. 

    Correct me if im wrong...

    - Are you telling me that adding multipart-form-Data with name attribute on the imputs will automatically handle my model variable? (enumerable httpPostedFileBase Files)

    -I dont have to create any controller or something like that? 

    Tuesday, April 14, 2020 8:31 PM
  • User475983607 posted

    MVC_user

    I didnt understand a word of what you say about mimes, but i believe you. 

    Correct me if im wrong...

    - Are you telling me that adding multipart-form-Data with name attribute on the imputs will automatically handle my model variable? (enumerable httpPostedFileBase Files)

    -I dont have to create any controller or something like that? 

    I do not understand your response. 

    I created a basic example (see below) that came from this blog; https://www.mikesdotnetting.com/article/287/uploading-multiple-files-with-asp-net-mvc.

    The key part to understand is the name attribute of both file inputs is files.  This is interpreted as a collection of files by the model binder.  Also an HTML Forms standard.

    @{
        ViewBag.Title = "Index";
    }
    
    <h2>File Upload Demo</h2>
    
    
    <form method="post" enctype="multipart/form-data">
        <div>
            <input type="file" name="files" />
        </div>
        <div>
            <input type="file" name="files" />
        </div>
        <div>
            <input id="Submit1" type="submit" value="submit" />
        </div>
    </form>
            [HttpGet]
            public ActionResult Index()
            {
                return View();
            }
    
            [HttpPost]
            public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
            {
                foreach (var file in files)
                {
                    if (file != null && file.ContentLength > 0)
                    {
                        file.SaveAs(Path.Combine(Server.MapPath("/uploads"), Guid.NewGuid() + Path.GetExtension(file.FileName)));
                    }
                }
                return View();
            }

    Tuesday, April 14, 2020 9:12 PM
  • User210306721 posted

    Im getting the idea, but what happens with the other information? 

    i mean on your Action you are saving only the files. And i must save a ViewModel too. 

    However if we save the both on the same action result and a user send a form whitout files, httppostedfilebase will not allow nulls. 

     

    Wednesday, April 15, 2020 12:36 PM
  • User475983607 posted

    Im getting the idea, but what happens with the other information? 

    i mean on your Action you are saving only the files. And i must save a ViewModel too. 

    However if we save the both on the same action result and a user send a form whitout files, httppostedfilebase will not allow nulls. 

     

    Take advantage of the "Model" in MVC.

    public class FileUploadDemo
    {
        public string Message { get; set; }
        public IEnumerable<HttpPostedFileBase> files { get; set; }
    }
    [HttpPost]
    public ActionResult Index(FileUploadDemo model)
    {
        foreach (var file in model.files)
        {
            if (file != null && file.ContentLength > 0)
            {
                file.SaveAs(Path.Combine(Server.MapPath("/uploads"), Guid.NewGuid() + Path.GetExtension(file.FileName)));
            }
        }
        ViewBag.Message = model.Message;
        return View();
    }
    @{
        ViewBag.Title = "Index";
    }
    
    <h2>File Upload Demo</h2>
    
    
    <form method="post" enctype="multipart/form-data">
        <div>
            <input id="Message" type="text" name="Message" value="Hello World" />
        </div>
        <div>
            <input type="file" name="files" />
        </div>
        <div>
            <input type="file" name="files" />
        </div>
        <div>
            <input id="Submit1" type="submit" value="submit" />
        </div>
    </form>
    @if(@ViewBag.Message != null)
    {
    <h2>
        @ViewBag.Message
    </h2>
    }

    I recommend that you stop coding for a while and learn MVC and HTTP.

    Wednesday, April 15, 2020 1:08 PM
  • User210306721 posted

    Look, maybe your are tired, and maybe i look as an ignorant, but im doing exactly that and does not working. (files are in null on the Model) 

    My model: 

    public IEnumerable<HttpPostedFileBase> files { get; set; }

    My Controller:

            public ActionResult Save([Bind] NotificationViewModel viewModel)
            {
    
                foreach (var file in viewModel.files)
                {
                    if (file != null && file.ContentLength > 0)
                    {
                        Console.WriteLine("Success");
                        //file.SaveAs(Path.Combine(Server.MapPath("/uploads"), Guid.NewGuid() + Path.GetExtension(file.FileName)));
                    }
                }
    
                viewModel.Save(viewModel);
                return TableNotification();
            }

    My html:

     @using (Html.BeginForm("Save", "Notification", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
                <label>Asunto:</label><br />
                @Html.InputFormFor(m => m.notification.Subject)
                <label>Título:</label><br />
                @Html.InputFormFor(m => m.notification.Title)
                <label>Sub Título:</label><br />
                @Html.InputFormFor(m => m.notification.SubTitle)
                <label>Descripción:</label><br />
                @Html.TextAreaFor(m => m.notification.MainText, new { })<br />
    
                <label>Elegir imagen de vista previa:</label><br />
    
                <input type="button" value="Eliminar Archivo" id="clear1" class="clear" style="color:black; float: left;" onclick="obj=document.getElementById('control1');obj.value='';obj.disabled=false">
                <input type="file" name="files" id="control1" class="UploadFile1" style="float: left;" onchange="this.disabled=true;">
                <br />
                <br />
                <label>Elegir imagen de contenido:</label>
                <br />
                <input type="button" value="Eliminar Archivo" id="clear2" class="clear" style="color:black; float: left;" onclick="obj=document.getElementById('control2');obj.value='';obj.disabled=false">
                <input type="file" name="files" id="control2" class="UploadFile2" style="float: left;" onchange="this.disabled=true;">
                <br />
                <br />
    
    ...

    Wednesday, April 15, 2020 1:25 PM
  • User475983607 posted

    Look, maybe your are tired, and maybe i look as an ignorant, but im doing exactly that and does not working. (files are in null on the Model) 

    My sample code functions as expected.  Your code disables the file inputs.  Browsers do not submit disabled fields.  Once I remove the onchange event the files upload as expected.

    <form method="post" enctype="multipart/form-data">
        <div>
            <input id="Message" type="text" name="Message" value="Hello World" />
        </div>
    
        <input type="button"
               value="Eliminar Archivo"
               id="clear1" class="clear"
               style="color:black; float: left;"
               onclick="obj=document.getElementById('control1');obj.value='';obj.disabled=false">
        <input type="file" name="files" id="control1" class="UploadFile1" style="float: left;">
        <br />
        <br />
        <label>Elegir imagen de contenido:</label>
        <br />
        <input type="button"
               value="Eliminar Archivo"
               id="clear2" class="clear"
               style="color:black; float: left;"
               onclick="obj=document.getElementById('control2');obj.value='';obj.disabled=false">
        <input type="file" name="files" id="control2" class="UploadFile2" style="float: left;">
        <br />
        <br />
        <div>
            <input id="Submit1" type="submit" value="submit" />
        </div>
    </form>



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, April 15, 2020 2:07 PM
  • User210306721 posted

    Omg you got right!!! 

    now i will try to fix it whitout lose that functionality. 

    Thanks a lot, my apologies.

    Wednesday, April 15, 2020 2:17 PM