locked
Ajax POST in MVC RRS feed

  • Question

  • User1554758465 posted

    I'm working with MVC Project and the following ajax doesn't work as expected i want the data to be passed to the Create action in Story Controller, which for now they are NULL when the ajax are called.

    I want to receive the data as parameters in my action:

    [HttpPost]    
    public async Task<IActionResult> Create(CreateStoryViewModel model, string count, List<string> val){}

    Script:

    <script>
        $(document).ready(function () {
            var counter = 0;
            $("#addrow").on("click", function () {
                var newRow = $("<tr>");
                var cols = "";
                cols += '<td class="col-md-3"><input type="text" class="form-control" name="sent" asp-for="Sentence.SentenceText" /></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="file" class="form-control-file border" name="aud"></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) {
                $(this).closest("tr").remove();
                counter -= 1
            });
            $('#publish').click(function () {
                var values = [];
                $('input[name="sent"]').each(function (i, elem) {
                    values.push($(elem).val());
                });
                alert(values.join(', '));
                alert(counter);
                $.ajax({
                    type: "POST",
                    url: "/Story/Create",
                    data: {
                        count: counter,
                        val: values
                    },
                    //contentType: "application/json; charset=utf-8",
                    dataType: 'json',
                    success: function (data) {
                    },
                    error: function (data) {
                    }
                });
            });
        });
    </script>
    <input type="submit" value="Publish" name="btn" id="publish" class="btn btn-default btn-block btn-icon" />

    Thursday, August 6, 2020 11:04 AM

Answers

  • User475983607 posted

    Your code has a lot of issues.  I'll address your null action parameters directly. The code below works.  Keep in mind your JavaScript code does not pass CreateStoryViewModel so that will always be null.

    @{
        ViewData["Title"] = "Index";
    }
    
    <h1>Index</h1>
    <div>
        <table class="order-list">
            <thead>
                <tr>
                    <td>1</td>
                    <td>2</td>
                    <td>3</td>
                    <td>4</td>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td class="col-md-3"><input type="text" class="form-control" name="sent" value="test 1" /></td>
                    <td class="col-md-1"><input type="file" class="form-control-file border" name="img"></td>
                    <td class="col-md-1"><input type="file" class="form-control-file border" name="aud"></td>
                    <td class="col-md-1"><input type="button" class="ibtnDel btn btn-md btn-danger " value="delete"></td>
                </tr>
                <tr>
                    <td class="col-md-3"><input type="text" class="form-control" name="sent" value="test 2" /></td>
                    <td class="col-md-1"><input type="file" class="form-control-file border" name="img"></td>
                    <td class="col-md-1"><input type="file" class="form-control-file border" name="aud"></td>
                    <td class="col-md-1"><input type="button" class="ibtnDel btn btn-md btn-danger " value="delete"></td>
                </tr>
            </tbody>
        </table>
        <hr />
        <div>
            <input id="addrow" type="button" value="Add Row" />
        </div>
        <div>
            <input id="publish" type="button" value="Publish" />
        </div>
    </div>
    
    
    
    
    @section scripts {
        <script>
            $(document).ready(function () {
                var counter = $('tbody tr').length;
                $("#addrow").on("click", function () {
                    var newRow = $("<tr>");
                    var cols = "";
                    cols += '<td class="col-md-3"><input type="text" class="form-control" name="sent" value="dynamic" /></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="file" class="form-control-file border" name="aud"></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
                });
    
                $('#publish').click(function () {
                    var values = [];
    
                    $('input[name="sent"]').each(function (i, elem) {
                        values.push($(elem).val());
                    });
    
                    console.log(values.join(', '));
                    console.log(counter);
    
                    $.ajax({
                        type: "POST",
                        url: "/Story/Create",
                        data: {
                            count: counter,
                            val: values
                        },
                        dataType: 'json',
                        success: function (data) {
                            console.log(data);
                            //Do something with the response
                        },
                        error: function (data) {
                            console.log("------Error------");
                            console.log(data);
                        }
                    });
                });
            });
        </script>
    }
    
    

    The delete click will not work with the dynamically created rows because the row did not exist when the page loaded.  

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 6, 2020 12:59 PM
  • User711641945 posted

    Hi ShahadAlshuhail,

    It could work well in my project.Could you share your whole razor view?

    My working demo:

    <table class="order-list">
        <tbody>
            <tr>
                <td><input type="text" class="form-control" name="sent" value="aaa" /></td>
            </tr>
            <tr>
                <td><input type="text" class="form-control" name="sent" value="bbb" /></td>
            </tr>
        </tbody>
    </table>
    <input type="submit" value="Publish" name="btn" id="publish" class="btn btn-default btn-block btn-icon" />
    
    @section Scripts
    {
        <script>
            $(document).ready(function () {
                $('#publish').click(function () {
                    var values = [];
                    $('input[name="sent"]').each(function (i, elem) {
                        values.push($(elem).val());
                    });
                    $.ajax({
                        type: "POST",
                        url: "/Story/Create",
                        data: {
                            count: 5,
                            val: values
                        },
                        dataType: 'json',
                        success: function (data) {
                        },
                        error: function (data) {
                        }
                    });
                });
            });
        </script>
    }

    Result:

    If you want to pass the model to the controller,change like below:

    <script>
        $(document).ready(function () {
            $('#publish').click(function () {
                var values = [];
                $('input[name="sent"]').each(function (i, elem) {
                    values.push($(elem).val());
                });
                $.ajax({
                    type: "POST",
                    url: "/Story/Create",
                    data: {
                        count: 5,
                        val: values,
                        model: {
                            id: 1,
                            name:"aaaa"
                        }
                    },
                    dataType: 'json',
                    success: function (data) {
                    },
                    error: function (data) {
                    }
                });
            });
        });
    </script>

    My testing model:

    public class CreateStoryViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, August 7, 2020 8:30 AM

All replies

  • User475983607 posted

    Your code has a lot of issues.  I'll address your null action parameters directly. The code below works.  Keep in mind your JavaScript code does not pass CreateStoryViewModel so that will always be null.

    @{
        ViewData["Title"] = "Index";
    }
    
    <h1>Index</h1>
    <div>
        <table class="order-list">
            <thead>
                <tr>
                    <td>1</td>
                    <td>2</td>
                    <td>3</td>
                    <td>4</td>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td class="col-md-3"><input type="text" class="form-control" name="sent" value="test 1" /></td>
                    <td class="col-md-1"><input type="file" class="form-control-file border" name="img"></td>
                    <td class="col-md-1"><input type="file" class="form-control-file border" name="aud"></td>
                    <td class="col-md-1"><input type="button" class="ibtnDel btn btn-md btn-danger " value="delete"></td>
                </tr>
                <tr>
                    <td class="col-md-3"><input type="text" class="form-control" name="sent" value="test 2" /></td>
                    <td class="col-md-1"><input type="file" class="form-control-file border" name="img"></td>
                    <td class="col-md-1"><input type="file" class="form-control-file border" name="aud"></td>
                    <td class="col-md-1"><input type="button" class="ibtnDel btn btn-md btn-danger " value="delete"></td>
                </tr>
            </tbody>
        </table>
        <hr />
        <div>
            <input id="addrow" type="button" value="Add Row" />
        </div>
        <div>
            <input id="publish" type="button" value="Publish" />
        </div>
    </div>
    
    
    
    
    @section scripts {
        <script>
            $(document).ready(function () {
                var counter = $('tbody tr').length;
                $("#addrow").on("click", function () {
                    var newRow = $("<tr>");
                    var cols = "";
                    cols += '<td class="col-md-3"><input type="text" class="form-control" name="sent" value="dynamic" /></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="file" class="form-control-file border" name="aud"></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
                });
    
                $('#publish').click(function () {
                    var values = [];
    
                    $('input[name="sent"]').each(function (i, elem) {
                        values.push($(elem).val());
                    });
    
                    console.log(values.join(', '));
                    console.log(counter);
    
                    $.ajax({
                        type: "POST",
                        url: "/Story/Create",
                        data: {
                            count: counter,
                            val: values
                        },
                        dataType: 'json',
                        success: function (data) {
                            console.log(data);
                            //Do something with the response
                        },
                        error: function (data) {
                            console.log("------Error------");
                            console.log(data);
                        }
                    });
                });
            });
        </script>
    }
    
    

    The delete click will not work with the dynamically created rows because the row did not exist when the page loaded.  

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 6, 2020 12:59 PM
  • User711641945 posted

    Hi ShahadAlshuhail,

    It could work well in my project.Could you share your whole razor view?

    My working demo:

    <table class="order-list">
        <tbody>
            <tr>
                <td><input type="text" class="form-control" name="sent" value="aaa" /></td>
            </tr>
            <tr>
                <td><input type="text" class="form-control" name="sent" value="bbb" /></td>
            </tr>
        </tbody>
    </table>
    <input type="submit" value="Publish" name="btn" id="publish" class="btn btn-default btn-block btn-icon" />
    
    @section Scripts
    {
        <script>
            $(document).ready(function () {
                $('#publish').click(function () {
                    var values = [];
                    $('input[name="sent"]').each(function (i, elem) {
                        values.push($(elem).val());
                    });
                    $.ajax({
                        type: "POST",
                        url: "/Story/Create",
                        data: {
                            count: 5,
                            val: values
                        },
                        dataType: 'json',
                        success: function (data) {
                        },
                        error: function (data) {
                        }
                    });
                });
            });
        </script>
    }

    Result:

    If you want to pass the model to the controller,change like below:

    <script>
        $(document).ready(function () {
            $('#publish').click(function () {
                var values = [];
                $('input[name="sent"]').each(function (i, elem) {
                    values.push($(elem).val());
                });
                $.ajax({
                    type: "POST",
                    url: "/Story/Create",
                    data: {
                        count: 5,
                        val: values,
                        model: {
                            id: 1,
                            name:"aaaa"
                        }
                    },
                    dataType: 'json',
                    success: function (data) {
                    },
                    error: function (data) {
                    }
                });
            });
        });
    </script>

    My testing model:

    public class CreateStoryViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, August 7, 2020 8:30 AM
  • User1554758465 posted

    Thank you Mr. mgebhard your modifications worked as expected. Now , i’m focusing on passing the model too

    Saturday, August 8, 2020 10:59 AM
  • User1554758465 posted

    Thank you Rena. Your model part helped me a lot. i highly appreciate your work. I think the problem was because i had multiple inputs of type “submit”

    Saturday, August 8, 2020 11:01 AM