locked
How to post a list of images via Ajax RRS feed

  • Question

  • User1185448985 posted

    I'm working with asp.net core MVC project and i want to post a list of images with there corresponding text input

    i want to combine the image list with values list to pass it to the controller in the form of something like :

    values [sentence][image]

    HTML

    @model TestApplication.Models.ViewModels.CreateStoryViewModel
    <form method="post" id="myForm" enctype="multipart/form-data">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="row">
            <div>
                <div class="row">
                    <div class="col-md-12">
                        <table id="table-2" class="table order-list datatable">
                            <thead>
                                <tr>
                                    <td class="col-md-6">
                                        <h4>
                                            Sentence
                                        </h4>
                                    </td>
                                    <td class="col-md-2">
                                        <h4>
                                            Image
                                        </h4>
                                    </td>
                                    <td class="col-md-2">
                                        <a class="deleteRow"></a>
                                        <h4>
                                            Delete
                                        </h4>
                                    </td>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td class="col-md-3"><input type="text" class="form-control" name="sent" /></td>
                                    <td class="col-md-1"><input type="file" class="form-control-file border" name="img"></td>
                                    <td class="col-md-1"><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>
                                </tr>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td>
                                        <input type="button" class="btn btn-primary btn-lg btn-block " id="addrow" value="Add" />
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
    
                    </div>
                </div>
            </div>
            <hr />
            <div class="col-md-12">
                <div class="text-center">
                    <input type="submit" id="create" value="Create" class="btn btn-success btn-block btn-icon" />
                    <button type="button" class="btn btn-danger btn-block btn-icon">Cancel</button>
                </div>
            </div>
    
        </div>
    </form>

    SCRIPT

    @section Scripts
    {
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js"></script>
    
        <script type="text/javascript">
            var counter = $('tbody tr').length;
    
            $(document).ready(function () {
                $("#addrow").on("click", function () {
                    var newRow = $("<tr>");
                    var cols = "";
                    cols += '<td class="col-md-3"><input type="text" class="form-control" name="sent" /></td>';
                    cols += '<td class="col-md-1"><input type="file" class="form-control-file border" name="img"></td>';
                    cols += '<td class="col-md-1"><input type="button" class="ibtnDel btn btn-md btn-danger" value="Delete"></td><hr />';
    
                    newRow.append(cols);
                    $('tbody').append(newRow);
                    counter++;
                });
    
            });
    
            $("table.order-list").on("click", ".ibtnDel", function (event) {
                console.log("Delete");
                $(this).closest("tr").remove();
                counter -= 1
            });
            $('#myForm').submit(function (e) {
                e.preventDefault();
                var vmodel = new FormData($('#myForm')[0]);
    .................
    .................
    var values = [];
    $('input[name="sent"]').each(function (i, elem) {
    values.push($(elem).val());
    }); $.ajax({ type: "POST", url: "/Story/Create", data: { model: { //stuff }, sentences: values, sentCount: counter }, dataType: 'json', success: function (data) { console.log(data) }, error: function (data) { } }); }); </script> }

    Controller:

            [HttpPost]
            public async Task<IActionResult> Create(CreateStoryViewModel model, string sentCount, List<string> sentences)



    Wednesday, August 12, 2020 11:24 PM

Answers

  • User711641945 posted

    Hi Amani AI,

    i want to combine the image list with values list to pass it to the controller in the form of something like :

    values [sentence][image]

    Did you mean that you want to send values below to the action and the value combine with sentence and image?

    data: {
              model: {
                //stuff
              },
              sentences: values,
              sentCount: counter
    }

    You need to know that you could not combine string and IFormfile data as a string type to the backend.If you want to get the image message and save it to the server side,you need to make the sentence and IFormFile as a model object.

    Here is a working demo about how to make the value as a string:

    <form method="post" id="myForm" enctype="multipart/form-data">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="row">
            <div>
                <div class="row">
                    <div class="col-md-12">
                        <table id="table-2" class="table order-list datatable">
                            <thead>
                                <tr>
                                    <td class="col-md-6">
                                        <h4>
                                            Sentence
                                        </h4>
                                    </td>
                                    <td class="col-md-2">
                                        <h4>
                                            Image
                                        </h4>
                                    </td>
                                    <td class="col-md-2">
                                        <a class="deleteRow"></a>
                                        <h4>
                                            Delete
                                        </h4>
                                    </td>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td class="col-md-3"><input type="text" class="form-control" name="sent" value="" /></td>
                                    <td class="col-md-1"><input type="file" class="form-control-file border" name="img" multiple /></td>
                                    <td class="col-md-1"><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>
    
                                </tr>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td>
                                        <input type="button" class="btn btn-primary btn-lg btn-block " id="addrow" value="Add" />
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
    
    
                    </div>
                </div>
            </div>
            <hr />
            <div class="col-md-12">
                <div class="text-center">
                    <input type="submit" id="create" value="Create" class="btn btn-success btn-block btn-icon" />
                    <button type="button" class="btn btn-danger btn-block btn-icon">Cancel</button>
                </div>
            </div>
        </div>
    </form>
    @section Scripts
    {
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="https://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js"></script>
        <script type="text/javascript">
            var counter = $('tbody tr').length;
            $(document).ready(function () {
                $("#addrow").on("click", function () {
                    var newRow = $("<tr>");
                    var cols = "";
                    cols += '<td class="col-md-3"><input type="text" class="form-control" name="sent" value=""/></td>';
                    cols += '<td class="col-md-1"><input type="file" class="form-control-file border" name="img"></td>';
                    cols += '<td class="col-md-1"><input type="button" class="ibtnDel btn btn-md btn-danger" value="Delete"></td><hr />';
                    newRow.append(cols);
                    $('tbody').append(newRow);
                    counter++;
                });
            });
            $("table.order-list").on("click", ".ibtnDel", function (event) {
                console.log("Delete");
                $(this).closest("tr").remove();
                counter -= 1
            });
            $('#myForm').submit(function (e) {
                e.preventDefault();
                var formData = new FormData($('#myForm')[0]);
                var value1 = formData.getAll("img");
                var values = [];
                $('input[name="sent"]').each(function (i, elem) {
                    formData.append('sentences[' + i + ']', $(elem).val()+','+value1[i].name);
                });
                formData.append('sentCount', counter);
                $.ajax({
                    type: "POST",
                    url: "/Story/Create",
                    async: true,
                    data: formData,
                    cache: false,
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        console.log("Ok")
                    },
                    error: function (data) {
                    }
                });
        </script>
    
    
    }
    

    Result:

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 13, 2020 9:37 AM

All replies

  • User711641945 posted

    Hi Amani AI,

    i want to combine the image list with values list to pass it to the controller in the form of something like :

    values [sentence][image]

    Did you mean that you want to send values below to the action and the value combine with sentence and image?

    data: {
              model: {
                //stuff
              },
              sentences: values,
              sentCount: counter
    }

    You need to know that you could not combine string and IFormfile data as a string type to the backend.If you want to get the image message and save it to the server side,you need to make the sentence and IFormFile as a model object.

    Here is a working demo about how to make the value as a string:

    <form method="post" id="myForm" enctype="multipart/form-data">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="row">
            <div>
                <div class="row">
                    <div class="col-md-12">
                        <table id="table-2" class="table order-list datatable">
                            <thead>
                                <tr>
                                    <td class="col-md-6">
                                        <h4>
                                            Sentence
                                        </h4>
                                    </td>
                                    <td class="col-md-2">
                                        <h4>
                                            Image
                                        </h4>
                                    </td>
                                    <td class="col-md-2">
                                        <a class="deleteRow"></a>
                                        <h4>
                                            Delete
                                        </h4>
                                    </td>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td class="col-md-3"><input type="text" class="form-control" name="sent" value="" /></td>
                                    <td class="col-md-1"><input type="file" class="form-control-file border" name="img" multiple /></td>
                                    <td class="col-md-1"><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>
    
                                </tr>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td>
                                        <input type="button" class="btn btn-primary btn-lg btn-block " id="addrow" value="Add" />
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
    
    
                    </div>
                </div>
            </div>
            <hr />
            <div class="col-md-12">
                <div class="text-center">
                    <input type="submit" id="create" value="Create" class="btn btn-success btn-block btn-icon" />
                    <button type="button" class="btn btn-danger btn-block btn-icon">Cancel</button>
                </div>
            </div>
        </div>
    </form>
    @section Scripts
    {
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="https://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js"></script>
        <script type="text/javascript">
            var counter = $('tbody tr').length;
            $(document).ready(function () {
                $("#addrow").on("click", function () {
                    var newRow = $("<tr>");
                    var cols = "";
                    cols += '<td class="col-md-3"><input type="text" class="form-control" name="sent" value=""/></td>';
                    cols += '<td class="col-md-1"><input type="file" class="form-control-file border" name="img"></td>';
                    cols += '<td class="col-md-1"><input type="button" class="ibtnDel btn btn-md btn-danger" value="Delete"></td><hr />';
                    newRow.append(cols);
                    $('tbody').append(newRow);
                    counter++;
                });
            });
            $("table.order-list").on("click", ".ibtnDel", function (event) {
                console.log("Delete");
                $(this).closest("tr").remove();
                counter -= 1
            });
            $('#myForm').submit(function (e) {
                e.preventDefault();
                var formData = new FormData($('#myForm')[0]);
                var value1 = formData.getAll("img");
                var values = [];
                $('input[name="sent"]').each(function (i, elem) {
                    formData.append('sentences[' + i + ']', $(elem).val()+','+value1[i].name);
                });
                formData.append('sentCount', counter);
                $.ajax({
                    type: "POST",
                    url: "/Story/Create",
                    async: true,
                    data: formData,
                    cache: false,
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        console.log("Ok")
                    },
                    error: function (data) {
                    }
                });
        </script>
    
    
    }
    

    Result:

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 13, 2020 9:37 AM
  • User1185448985 posted

    This is how i did

    @section Scripts
    {
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js"></script>
    
        <script type="text/javascript">
            var counter = $('tbody tr').length;
    
            $(document).ready(function () {
                $("#addrow").on("click", function () {
                    var newRow = $("<tr>");
                    var cols = "";
                    cols += '<td class="col-md-3"><input type="text" class="form-control" name="sent" /></td>';
                    cols += '<td class="col-md-1"><input type="file" class="form-control-file border" name="img"></td>';
                    cols += '<td class="col-md-1"><input type="button" class="ibtnDel btn btn-md btn-danger" value="Delete"></td><hr />';
    
                    newRow.append(cols);
                    $('tbody').append(newRow);
                    counter++;
                });
    
            });
    
            $("table.order-list").on("click", ".ibtnDel", function (event) {
                console.log("Delete");
                $(this).closest("tr").remove();
                counter -= 1
            });
            $('#myForm').submit(function (e) {
               e.preventDefault();
                var data = new FormData($('#myForm')[0]);
                var files = data.get("img");
    
                for (var i = 0; i < files.length; i++) {
                    data.append("File", files[i]);
                }
                $('input[name="sent"]').each(function (i, elem) {
                    data.append('sentences[' + i + ']', $(elem).val());
                });
    
                $.ajax({
                    type: "POST",
                    url: "/Story/Create",
                    contentType: false,
                    processData: false,
                    data: data,
                    success: function (message) {
                        window.location.href = "Index";
                    },
                    error: function () {
                        alert("There was error uploading files!");
                    }
                });
            });
    
        </script>
    
    }

    And i combined the sentences list with images using Zip() in the action:

    [HttpPost]
    public async Task<IActionResult> Create(CreateStoryViewModel model,....., List<string> sentences){

    .....

    var files = HttpContext.Request.Form.Files;
    var sentencesAndImages = files.Zip(sentences, (i, s) => new { Image = i, Sentence = s });

    .......
    }
    Friday, August 14, 2020 8:38 PM