Populate ASP.Net DropDownList inside Bootstrap Modal Popup using jQuery Ajax and Json

ramco1917
 
on Sep 06, 2022 11:12 PM
Sample_817107.zip
626 Views

Hi

I have below code & i want when clicked on Add, modal popup opens & in DropDownList i want to display States of selected record.

try
{
    StringBuilder htmlTable = new StringBuilder();
    string ParticipantType = "";
 
    BALTrainingHeader bALTrainingHeader = new BALTrainingHeader();
    List<TrainingHeader> Result = bALTrainingHeader.GetRecordListDrafted();
 
    if (Result != null)
    {
        BALEmployee bALEmployee = new BALEmployee();
        htmlTable.Append("<table class='table table-bordered table-hover datatable-highlight' id='tbldata'>");
 
        htmlTable.Append("<thead><tr><th style='display:none'>#</th><th>Training Number</thth class='text-center nosort'>Actions</th><th class='text-center nosort'>Add</th></tr></thead>");
        htmlTable.Append("<tbody>");
        foreach (var colum in Result)
        {                       
            htmlTable.Append("<tr>");
            htmlTable.Append("<td style='display:none'>" + colum.TrainingID + "</td>");
            htmlTable.Append("<td>" + colum.TrainingNumber + "</td>");
             
            htmlTable.Append("<td class='text-center'> <a id='btnEdit' style='cursor:pointer;' class='list-icons-item text-primary-600' title='Edit' href='NewTraining.aspx?val=" + AES.Encrypt(colum.TrainingID.ToString()) + "'><i class='icon-pencil7 mr-1'></i>  </a>" + "</td>");
            htmlTable.Append("<td class='text-center'> <a id='btnAdd' style='cursor:pointer;' class='list-icons-item text-primary-600' data-toggle='modal' data-backdrop='static' data-keyboard='false' data-target='#modal_form_horizontal' onclick='BindData(this);'><i class='icon-pencil7 mr-1'></i></a></td>");
 
            htmlTable.Append("</tr>");
        }
        htmlTable.Append("</tbody>");
        htmlTable.Append("</table>");
 
        PlaceHolderTable.Controls.Add(new Literal { Text = htmlTable.ToString() });
    }
}

 

<div id="modal_form_horizontal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-info">
                <h5 class="modal-title">Add/Update Record</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>&nbsp;                                  
            </div>
            <div class="form-horizontal">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-lg-6">
                            <div class="form-group">
                                <label>State</label>&nbsp;<span style="color: red">*</span>
                                <asp:DropDownList ID="ddlState" class="form-control" runat="server" required="true">
                                    <asp:ListItem Value="">Select State</asp:ListItem>
                                </asp:DropDownList>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
</div>

 

<script type="text/javascript">
    function BindData(e) {
        var currentRow = $(e).closest("tr");
        var Id = currentRow.find("td:eq(0)").text();
        document.getElementById('txtId').value = Id;
    };
</script>

Thanks

Download FREE API for Word, Excel and PDF in ASP.Net: Download
KasimA
 
on Sep 07, 2022 07:24 AM

Hi ramco1917,

Please refer below sample.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

HTML

<div class="container-fluid">
    <asp:PlaceHolder ID="PlaceHolderTable" runat="server"></asp:PlaceHolder>
</div>
<div id="modal_form_horizontal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-info">
                <h5 class="modal-title">Add/Update Record</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>&nbsp; 
            </div>
            <div class="form-horizontal">
                <div class="modal-body" style="padding-left: 40px;">
                    <div class="row">
                        <div class="col-lg-6">
                            <div class="form-group">
                                <label>Order</label>&nbsp;<span style="color: red">*</span>
                                <asp:DropDownList ID="ddlOrders" class="form-control" runat="server" required="true">
                                </asp:DropDownList>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
</div>
<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://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script type="text/javascript">
    function BindData(ele) {
        var id = $(ele).closest('tr').find('td').eq(0).html();
        $.ajax({
            type: "POST",
            url: "CS.aspx/GetOrders",
            data: '{id:"' + id + '"}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                var ddlOrders = $("[id*=ddlOrders]");
                ddlOrders.empty().append('<option selected="selected" value="0">Select Order</option>');
                $.each(r.d, function () {
                    ddlOrders.append($("<option></option>").val(this['Value']).html(this['Text']));
                });
                $('#modal_form_horizontal').modal("show");
            }
        });
    };
</script>

Namespaces

C#

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

VB.Net

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

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        StringBuilder htmlTable = new StringBuilder();
        htmlTable.Append("<table class='table table-bordered table-hover datatable-highlight' id='tbldata'>");
        htmlTable.Append("<thead><tr><th style='display:none;'>#</th><th>Name</th><th>Country</th><th class='text-center nosort'>Actions</th><th class='text-center nosort'>Add</th></tr></thead>");
        htmlTable.Append("<tbody>");
        foreach (var colum in GetData())
        {
            htmlTable.Append("<tr>");
            htmlTable.Append("<td style='display:none;'>" + colum.CustomerId + "</td>");
            htmlTable.Append("<td>" + colum.ContactName + "</td>");
            htmlTable.Append("<td>" + colum.Country + "</td>");
            htmlTable.Append("<td class='text-center'> <a id='btnEdit' style='cursor:pointer;' class='list-icons-item text-primary-600' title='Edit' href='NewTraining.aspx?val=" + colum.CustomerId.ToString() + "'><i class='icon-pencil7 mr-1'></i> Edit </a>" + "</td>");
            htmlTable.Append("<td class='text-center'> <a id='btnAdd' style='cursor:pointer;' class='list-icons-item text-primary-600' data-toggle='modal' data-backdrop='static' data-keyboard='false' onclick='BindData(this);'><i class='icon-pencil7 mr-1'></i>Add</a></td>");
            htmlTable.Append("</tr>");
        }
        htmlTable.Append("</tbody>");
        htmlTable.Append("</table>");

        PlaceHolderTable.Controls.Add(new Literal { Text = htmlTable.ToString() });
    }
}
public List<Data> GetData()
{
    List<Data> items = new List<Data>();
    items.Add(new Data { CustomerId = "ALFKI", ContactName = "Alfreds Futterkiste", Country = "UK" });
    items.Add(new Data { CustomerId = "ANATR", ContactName = "Around the Horn", Country = "Germany" });
    items.Add(new Data { CustomerId = "ANTON", ContactName = "Island Trading", Country = "France" });
    items.Add(new Data { CustomerId = "AROUT", ContactName = "La maison d'Asie", Country = "Canada" });
    return items;
}

[WebMethod]
public static List<ListItem> GetOrders(string id)
{
    List<ListItem> orders = new List<ListItem>();
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT OrderID,Freight FROM [Orders] WHERE CustomerID = @Id", con))
        {
            cmd.Parameters.AddWithValue("@Id", id);
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    orders.Add(new ListItem
                    {
                        Value = sdr["OrderID"].ToString(),
                        Text = sdr["Freight"].ToString()
                    });
                }
            }
            con.Close();
        }
    }
    return orders;
}

public class Data
{
    public string CustomerId { get; set; }
    public string ContactName { get; set; }
    public string Country { get; set; }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim htmlTable As StringBuilder = New StringBuilder()
        htmlTable.Append("<table class='table table-bordered table-hover datatable-highlight' id='tbldata'>")
        htmlTable.Append("<thead><tr><th style='display:none;'>#</th><th>Name</th><th>Country</th><th class='text-center nosort'>Actions</th><th class='text-center nosort'>Add</th></tr></thead>")
        htmlTable.Append("<tbody>")

        For Each colum In GetData()
            htmlTable.Append("<tr>")
            htmlTable.Append("<td style='display:none;'>" & colum.CustomerId & "</td>")
            htmlTable.Append("<td>" & colum.ContactName & "</td>")
            htmlTable.Append("<td>" & colum.Country & "</td>")
            htmlTable.Append("<td class='text-center'> <a id='btnEdit' style='cursor:pointer;' class='list-icons-item text-primary-600' title='Edit' href='NewTraining.aspx?val=" & colum.CustomerId.ToString() & "'><i class='icon-pencil7 mr-1'></i> Edit </a>" & "</td>")
            htmlTable.Append("<td class='text-center'> <a id='btnAdd' style='cursor:pointer;' class='list-icons-item text-primary-600' data-toggle='modal' data-backdrop='static' data-keyboard='false' onclick='BindData(this);'><i class='icon-pencil7 mr-1'></i>Add</a></td>")
            htmlTable.Append("</tr>")
        Next

        htmlTable.Append("</tbody>")
        htmlTable.Append("</table>")
        PlaceHolderTable.Controls.Add(New Literal With {
        .Text = htmlTable.ToString()
    })
    End If
End Sub

Public Function GetData() As List(Of Data)
    Dim items As List(Of Data) = New List(Of Data)()
    items.Add(New Data With {
        .CustomerId = "ALFKI",
        .ContactName = "Alfreds Futterkiste",
        .Country = "UK"
    })
    items.Add(New Data With {
        .CustomerId = "ANATR",
        .ContactName = "Around the Horn",
        .Country = "Germany"
    })
    items.Add(New Data With {
        .CustomerId = "ANTON",
        .ContactName = "Island Trading",
        .Country = "France"
    })
    items.Add(New Data With {
        .CustomerId = "AROUT",
        .ContactName = "La maison d'Asie",
        .Country = "Canada"
    })
    Return items
End Function

<WebMethod>
Public Shared Function GetOrders(ByVal id As String) As List(Of ListItem)
    Dim orders As List(Of ListItem) = New List(Of ListItem)()
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand("SELECT OrderID,Freight FROM [Orders] WHERE CustomerID = @Id", con)
            cmd.Parameters.AddWithValue("@Id", id)
            con.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    orders.Add(New ListItem With {
                    .Value = sdr("OrderID").ToString(),
                    .Text = sdr("Freight").ToString()
                })
                End While
            End Using
            con.Close()
        End Using
    End Using
    Return orders
End Function

Public Class Data
    Public Property CustomerId As String
    Public Property ContactName As String
    Public Property Country As String
End Class

Screenshot