locked
C# MVC Checkbox Javascript Ajax or C# Action which way should I do? RRS feed

  • Question

  • User-544325736 posted

    Hello everyone,

    I have a view that has a table with rows of records. In front of each row I added a separate checkbox. I am currently in the process of determinine if this checkbox ischecked or not. I was wondering if I should do my button click with javascript and ajax to determine what records have a selected checkbox with these checkboxes I will print out a rdlc report of what was selected. Or should I use a HTMLActionlink button to go straight to a controller and see what was selected. What way would be faster and better? Also what is the proper way I should do this? Here is what I currently have im very curious to hear what you all have to say. I have the id of each quote attached to the checkbox. I wanted to push the valid ones to an array but so far my current code doesn’t do it yet. I feel I am close to having it.

    MVC View
    <input type="button" class="btn btn-primary" name="command" id="btnGetChecks" value="Generate Selected" />
    <table class="table" id="maintbl"><thead>…</thead>
    <tbody id="maintblbody">
                    @for (int i = 0; i < Model.ListQuotes.Count; i++)
                    {
                        var current = Model.ListQuotes[i];
                        <tr>
                            <td>
                                @Html.CheckBox(i+"_Row", true, new { value = @Model.ListQuotes[i].QuoteID })
                                </td><td>
                                //<input type="checkbox" class="checkbox" name="checks" id="@(i + "_Row")" value="@Model.ListQuotes[i].QuoteID" />
                            </td>
                            @for (int j = 0; j < Model.Settings.Columns.Length; j++)
                            {
                                if (Model.Settings.Show[j])
                                {
                                    var quote = current.GetType().GetProperties().Where(x => x.Name.Equals(Model.Settings.Columns[j])).First();
                                    <td style="padding-right:20px;">@quote.GetValue(current, null)</td>
                                }
                            }
                            <td>
                                <button type="button" class="openModal btn btn-danger" data-quoteid="@Model.ListQuotes[i].QuoteID">
                                    Edit
                                </button>
                            </td>
                        </tr>
                    }
    </tbody>
    <script>
    $('#btnGetChecks').on('click', function () {
                var quotes = [];
                var quoteid = $(this).attr("value");
                var chkboxtable = $('#maintbl');
                var 
                //$('input:checked').each(function() {
                //    quotes.push($(this).attr("value"));
                //});    with 0 -  ^(0|\+?[1-9]\d*)$         /^-?[0-9]+$/
                // $(this).val($(this).val().replace(/[^\d].+/, ""));
                // if (!(keyCode >= 48 && keyCode <= 57)
                $('input[type=checkbox]').each(function () {
                    if (this.checked==true) {
                        if (IsPositiveInteger(quoteid)) {
                            quotes.push($(this).attr("value"));
    
                        }
                    }
                });
    
                alert(quotes);
            });
    <script>
    

    Tuesday, October 29, 2019 2:42 PM

Answers

  • User475983607 posted

    jQuery selector to get all the checked checkboxes.

    $( "input:checked" )

    https://api.jquery.com/checked-selector/

    Then to get the values.

    <form method="post">
        <input type="checkbox" value="1" checked />
        <input type="checkbox" value="2" />
        <input type="checkbox" value="3" checked />
        <input type="checkbox" value="4" />
        <input type="checkbox" value="5" checked />
    </form>
    
    @section scripts {
        <script>
            var quotes = [];
            $("input:checked").each(function (index, value) {
                quotes.push($(value).val());
            });
    
            console.log(quotes);
        </script>
    }
    

    ExceedingLife

    Or should I use a HTMLActionlink button to go straight to a controller and see what was selected.

    An ActionLink causes an HTTP GET so it is not an option unless you wire up a click handler and do an AJAX request.

    ExceedingLife

    Also what is the proper way I should do this?

    There's no proper way.  I think a form post is a bit easier.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, October 29, 2019 3:04 PM

All replies

  • User475983607 posted

    jQuery selector to get all the checked checkboxes.

    $( "input:checked" )

    https://api.jquery.com/checked-selector/

    Then to get the values.

    <form method="post">
        <input type="checkbox" value="1" checked />
        <input type="checkbox" value="2" />
        <input type="checkbox" value="3" checked />
        <input type="checkbox" value="4" />
        <input type="checkbox" value="5" checked />
    </form>
    
    @section scripts {
        <script>
            var quotes = [];
            $("input:checked").each(function (index, value) {
                quotes.push($(value).val());
            });
    
            console.log(quotes);
        </script>
    }
    

    ExceedingLife

    Or should I use a HTMLActionlink button to go straight to a controller and see what was selected.

    An ActionLink causes an HTTP GET so it is not an option unless you wire up a click handler and do an AJAX request.

    ExceedingLife

    Also what is the proper way I should do this?

    There's no proper way.  I think a form post is a bit easier.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, October 29, 2019 3:04 PM
  • User-544325736 posted

    I know this is really close.

    This is what I was getting before. 

    My values are true,true,true,true, for as many checkboxes there are then the selected(checked) one instead of 'true' it has the value of the value attribute. 

    What I was working on before was to make a function to determine if it was an int or not and only push the int values to the array.

    Do you think that would work? 
    This is what I originally had and heres my function to determine ints

    function IsPositiveInteger(number) {
                var expression = /^(0|\+?[1-9]\d*)$/;
                return expression.test(number);
            }

    //if (chktablebody.find($('input:checked'))) {
    
    $('input:checked').each(function () {
    //$('input[type=checkbox]').each(function () {
    //if (this.checked==true) {
    if (IsPositiveInteger(quoteid)) {
    quotes.push($(this).attr("value"));
    
    }
    });

    Here is what I did to Get all Selected Checkboxes into its own Array. Next ill pass it to a controller with ajax.

                // Turn all selected checkbox T/F values into QuoteIDs
                $("input:checked").each(function (index, value) {
                    arrChkBoxes.push($(value).val());
                });
                // Push all QuoteIDs into new array
                $.each(arrChkBoxes, function (key, value) {
                    if (IsPositiveInteger(value)) {
                        arrSelectedQIDs.push(value);
                    }
                });


    Tuesday, October 29, 2019 3:34 PM
  • User475983607 posted

    I'm having a hard time following your code and requirements.  You need all the check values that are positive integers?

    <form method="post">
        <input type="checkbox" value="1" checked />
        <input type="checkbox" value="2" />
        <input type="checkbox" value="A" checked />
        <input type="checkbox" value="4" checked />
        <input type="checkbox" value="-5" checked />
    </form>
    
    @section scripts {
        <script>
            var quotes = [];
            $("input:checked").each(function (index, value) {
                let val = $.isNumeric($(value).val()) ? parseInt($(value).val()) : -1;
                if (val > 0) {
                    quotes.push(val);
                }
            });
    
            console.log(quotes);
        </script>
    }

    Tuesday, October 29, 2019 6:16 PM
  • User-544325736 posted

    Sorry for the late reply.

    So currently every checkbox in my list comes back as 'true' or 'on' for some reason every checkbox comes back as that.

    When i check a checkbox the value comes back as the 'quoteid' such as 345 or whatever the id is.

    So I was checking every value in my list if its a number then it means the checkbox is selected. 

    This is the function I created to determine if the checkbox is selected (if its a number)

        function IsPositiveInteger(number) {
            var expression = /^(0|\+?[1-9]\d*)$/;
            return expression.test(number);
        }

    Why does the list always return a true or on value? im not sure. But if its a number it means its selected so I check each value in the list if its a number I add it to a new list/array and I pass that new list/array to the controller so I know that is the selected values.

    This is what I used is there a better way to do it? or is what i did fine? How would you do it?

    $('#btnGetChecksz').on('click', function () {
                var arrChkBoxes = [];
                var arrSelectedQIDs = [];
               
                // Turn all selected checkbox T/F values into QuoteIDs
                $("input:checked").each(function (index, value) {
                    arrChkBoxes.push($(value).val());
                });
                // Push all QuoteIDs into new array
                $.each(arrChkBoxes, function (key, value) {
                    if (IsPositiveInteger(value)) {
                        arrSelectedQIDs.push(value);
                    }
                });   
    
                $.ajax({
                    type: "GET",
                    url: "/Service/ExportReport/",
                    contentType: "application/json; charset=utf-8",
                    traditional: true,
                    data: { "quoteIDs": arrSelectedQIDs },
                    success: function (data) {
                        //alert("success");
                        window.location = '/Service/DownloadReport?mimeType=' + data;
                    },
                    error: function (request, status, error) {
                        alert("error " + request.responseText);
                    }
                });
            });

    Thank you

    Tuesday, November 5, 2019 4:22 PM
  • User475983607 posted

    This is what I used is there a better way to do it? or is what i did fine? How would you do it?

    I showed how to get the checked values in JavaScript.  So the next problem is you need the Ids too?

    <form method="post">
        <input id="1_row" type="checkbox" value="1" checked />
        <input id="2_row" type="checkbox" value="2" />
        <input id="3_row" type="checkbox" value="3" checked />
        <input id="4_row" type="checkbox" value="4" />
        <input id="5_row" type="checkbox" value="5" checked />
    </form>
    
    @section Scripts {
    <script>
        var quotes = [];
        $("input:checked").each(function (index, value) {
            quotes.push({
                id: $(value).prop('id'),
                value: $(value).val()
            });
        });
    
        console.log(quotes);
    </script>
    }

    You'll need to create a model in C# so the model binder can populate the new complex type.

           public class Quote
            {
                public int id { get; set; }
                public int value { get; set; }
            }

    Then the action input is,

    [HttpPost]
    public ActionResult Index(List<Quote> quotes)

    Tuesday, November 5, 2019 10:01 PM