Different way to pass (send) CheckBox value to Controller in ASP.Net MVC

Last Reply one year ago By dharmendr

Posted one year ago

C# MVC Checkbox Javascript Ajax or C# Action which way should I do

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');
           
            $('input[type=checkbox]').each(function () {
                if (this.checked==true) {
                    if (IsPositiveInteger(quoteid)) {
                        quotes.push($(this).attr("value"));

                    }
                }
            });

            alert(quotes);
        });
    <script>
Posted one year ago

Hi bigbear,

If you are using Html.BeginForm to submit the form then you can use Model to get the checked checkboxes in Controller Action method.

Refer below link.

Implement CheckBoxList in ASP.Net MVC

If you are not using Html.BeginForm then you have to use jQuery Ajax to call the Controller Action method to get the checked checkboxes.

If you want to any validation over CheckBoxes checked values then use jQuery for it.