Submit Checked (Selected) CheckBoxes in JSON format using jQuery and Ajax in ASP.Net

Sumeet
 
on Aug 28, 2022 11:50 PM
Sample_503644.zip
1218 Views

I have auto generated table with auto generated checkboxes on aspx page. Now I am reading all checked checkboxes ID and Value via jQuery JSON method on Button Click. 

I would need to submit the checked CheckBoxes data to SQL database and get saved in table.

Below is my code.

ASPX: 

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="CSS/assets/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link href="CSS/assets/dist/css/customstyl.css" rel="stylesheet" />
    <script src="CSS/assets/dist/js/jquery.min.js"></script>
    <script src="JS/Event.js"></script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <%--<input type="button" id="btnGenerate" value="Generate Table" />&nbsp;--%>
            <select id="DropDownListcols" class="form-control-sm">
                <option value="0">SELECT</option>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
            </select>
            &nbsp;
            <input type="submit" id="submitbutton" value="Submit" class="btn btn-primary btn-sm" />
             
            <hr />
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">
                        <div id="xmldisplay">

                        </div>
                        <div id="dvTable">
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </form>
</body>
</html>

Event.js: 

$(function () {
    $("#DropDownListcols").change(function () {
        //debugger;
        //Get the count of columns.
        var totalrows = 10;
        var columnCount = $(this).val();
        if (columnCount == 0) {
            columnCount = 4;
        }
        var colno = 0;
        //Create a HTML Table element.
        var table = '<table class="table table-bordered" id="Mastertable">';
        table += '<thead class="thead-dark freeze">';

        //Create table header according to number of columns
        for (var headcol = 0; headcol < columnCount; headcol++) {
            table += '<th>Column ' + (headcol + 1).toString() + '</th>';
        }
        table += '</thead>';
        table += '<tbody>';
        for (var j = 0; j < totalrows; j++) {
            table += '<tr>';
            for (var z = 0; z < columnCount; z++) {
                table += '<td>' + GetCheckBoxes(z + 1, j + 1) + '</td>';
            }
            table += '</tr>';
        }
        table += '</tbody></table>';

        $("#dvTable").html("");
        $("#dvTable").html(table);

    });

    $("#submitbutton").click(function (e) {
        e.preventDefault();
        //alert('Hello');
        SaveXMLDatatoDatabase();
    });
});

function SaveXMLDatatoDatabase() {
    //var XmlData = '', strXML = '', chkValue = '', chkID = '';
    debugger;
    var Rows = $('#Mastertable tbody tr');
    if (Rows.length > 0) {
        $("input:checkbox[name=cbox]:checked").each(function () {
             
            alert("Id: " + $(this).attr("id") + "\nValue: " + $(this).val());
            
        });
    }
 
}

function GetCheckBoxes(colcount, rowcount) {
    //debugger;
    var str = "";
    //str += '<table class="noborder"><tr>';
    str += '<div class="row"><div class="form-group">'
    for (chk = 0; chk < rowcount; chk++) {
        var chkid = 'Column_' + colcount.toString() + '_Row_' + rowcount.toString() + '_CHKID_' + (chk + 1).toString();
        str += '<label class="col-md-1 checkbox-inline" for="' + chkid.toString() + '">';
        str += '<input class="form-check-input floatleftwithPad" type = "checkbox" value = "' + chkid + '_Value' + '" id = "' + chkid + '" name="cbox">';
        str += '</label>';
    }
    str += '</div></div>';
    return str;
}

/* SUBMIT BUTTON Event To Get Checked Box ID */

customStyle.css:

.freeze {
    position:sticky;top:0;z-index:9999;
}
.floatleftwithPad {
    float:left!important;
    padding:6px;
}
input[type="radio"], input[type="checkbox"] {
    line-height: normal;
    margin: 0;     
    width:15px;height:15px;
}
 
table.noborder tbody tr td {
    border-style: none !important;
}
ul#chklisting {
    list-style-type:none;
}
ul#chklisting li {
    float:left;
    text-align:left;
}
Download FREE API for Word, Excel and PDF in ASP.Net: Download
PrinceG
 
on Aug 29, 2022 03:39 AM

Hi Sumeet,

Please refer below sample.

HTML

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/json2/20130526/json2.min.js"></script>
<div class="container">
    <select id="DropDownListcols" class="form-control-sm">
        <option value="0">SELECT</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select>
    &nbsp;
    <input type="submit" id="submitbutton" value="Submit" class="btn btn-primary btn-sm" />
</div>
<hr />
<div class="container">
    <div class="row">
        <div class="col-lg-12">
            <div id="xmldisplay">
            </div>
            <div id="dvTable">
            </div>
        </div>
    </div>
</div>
</form>
<script type="text/javascript">
    $(function () {
        $("#DropDownListcols").change(function () {
            //Get the count of columns.
            var totalrows = 10;
            var columnCount = $(this).val();
            if (columnCount == 0) {
                columnCount = 4;
            }
            var colno = 0;
            //Create a HTML Table element.
            var table = '<table class="table table-bordered" id="Mastertable">';
            table += '<thead class="thead-dark freeze">';

            //Create table header according to number of columns
            for (var headcol = 0; headcol < columnCount; headcol++) {
                table += '<th>Column ' + (headcol + 1).toString() + '</th>';
            }
            table += '</thead>';
            table += '<tbody>';
            for (var j = 0; j < totalrows; j++) {
                table += '<tr>';
                for (var z = 0; z < columnCount; z++) {
                    table += '<td>' + GetCheckBoxes(z + 1, j + 1) + '</td>';
                }
                table += '</tr>';
            }
            table += '</tbody></table>';
            $("#dvTable").html("");
            $("#dvTable").html(table);
        });

        $("#submitbutton").click(function (e) {
            e.preventDefault();
            SaveXMLDatatoDatabase();
        });
    });

    function SaveXMLDatatoDatabase() {
        var Rows = $('#Mastertable tbody tr');
        var checkedValue = [];
        if (Rows.length > 0) {
            $("input:checkbox[name=cbox]:checked").each(function () {
                var obj = {};
                obj.Id = $(this).attr("id");
                obj.Value = $(this).val();
                checkedValue.push(obj);
            });

            $.ajax({
                type: 'POST',
                url: 'Default.aspx/InsertChecked',
                data: JSON.stringify({ details: checkedValue }),
                contentType: 'application/json; charset=utf-8',
                DataType: 'json',
                success: function (r) {
                    alert(r.d);
                },
                error: function (r) {
                    alert(r.responseText);
                }
            });
        }
    }

    function GetCheckBoxes(colcount, rowcount) {
        var str = "";
        //str += '<table class="noborder"><tr>';
        str += '<div class="row"><div class="form-group">'
        for (chk = 0; chk < rowcount; chk++) {
            var chkid = 'Column_' + colcount.toString() + '_Row_' + rowcount.toString() + '_CHKID_' + (chk + 1).toString();
            str += '<label class="col-md-1 checkbox-inline" for="' + chkid.toString() + '">';
            str += '<input class="form-check-input floatleftwithPad" type = "checkbox" style="height:50px; width:5px" value = "' + chkid + '_Value' + '" id = "' + chkid + '" name="cbox">';
            str += '</label>';
        }
        str += '</div></div>';
        return str;
    }
</script>

Namespaces

C#

using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;

VB.Net

Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Services

Code

C#

[WebMethod]
public static void InsertChecked(List<Detail> details)
{
    foreach (Detail detail in details)
    {
        string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        string query = "INSERT INTO Table VALUES(@Id, @Value)";
        using (SqlConnection con = new SqlConnection(conString))
        {
            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                cmd.Parameters.AddWithValue("@Id", detail.Id);
                cmd.Parameters.AddWithValue("@Value", detail.Value);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
    }
}

public class Detail
{
    public string Id { get; set; }
    public string Value { get; set; }
}

VB.Net

<WebMethod()>
Public Shared Sub InsertChecked(ByVal details As List(Of Detail))
    For Each detail As Detail In details
        Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Dim query As String = "INSERT INTO Table VALUES(@Id, @Value)"
        Using con As SqlConnection = New SqlConnection(conString)
            Using cmd As SqlCommand = New SqlCommand(query, con)
                cmd.Parameters.AddWithValue("@Id", detail.Id)
                cmd.Parameters.AddWithValue("@Value", detail.Value)
                con.Open()
                cmd.ExecuteNonQuery()
                con.Close()
            End Using
        End Using
    Next
End Sub

Public Class Detail
    Public Property Id As String
    Public Property Value As String
End Class

Screenshot