Implement cascading DropDownList inside bootstrap Modal popup using PartialView in ASP.Net MVC

Last Reply 13 days ago By dharmendr

Posted 13 days ago

How to create cascading Dropdownlist inside modal popup

I have a partial view "_CreateRoom" inside modal popup. My problem is that the dropdownlist Campaign dosen't load when I select a Customer. I don't need to do "post" because I am using signalR for create rooms.

Index.cshtml

@{
    ViewBag.Title = "Index";
}
 
@section scripts{
    <script src="~/Scripts/knockout-3.4.2.js"></script>
    <script src="~/Scripts/modernizr-2.8.3.js"></script>
}
 
<div class="row main-container">
    <div class="col-md-2">
        <div class="menu">
            <a href="#" onclick="AddRooms()"><span class="glyphicon glyphicon-cog"></span>Crear Sala</a>
        </div>
    </div>
</div>

<div class="modal" id="create-room" data-backdrop="static">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title">New Room</h4>
            </div>
            <div class="modal-body" id="roomModalBody"></div>
        </div>
    </div>
</div>
<script>
    var AddRooms = function () {
        var url = "/Home/CreateRoom";
        $("#roomModalBody").load(url, function () {
            $("#create-room").modal("show");
        })
    }
</script>

HomeController

    public class HomeController : Controller
    {
        ApplicationDbContext app = new ApplicationDbContext()
        public ActionResult CreateRoom()
        {
            /*GetCustomers(): Get the Customer list.*/
            ViewBag.CustomerList = new SelectList(GetCustomers(), "ID", "Name");
            ViewBag.CampaignList = new SelectList(new List<Campaign>(), "ID", "Name");

            return PartialView("_CreateRoom");
        }
        public JsonResult GetCampaignList(int customerID)
        {
            /*GetCampaigns(customerID):  Get the campaigns by customerID*/
            return new JsonResult { Data = GetCampaigns(customerID), JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
    }

Models-> CreateViewModel class have three properties Customer ID, Campaign ID, Name.

_CreateRoom.cshtml

@using MyProyect.Models
@model CreateViewModel

<div>
    <form id="formRegister">
        <div class="row">
            <div class="col-md-12">
                @Html.AntiForgeryToken()
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group">
                    @Html.DropDownListFor(r => r.CustomerID, ViewBag.CustomerList as SelectList, "-- Select --", new { @class = "form-control" })
                </div>
                <div class="form-group">
                    @Html.DropDownListFor(r => r.CampaignID, ViewBag.CampaignList as SelectList, "-- Select --", new { @class = "form-control"})
                </div>
                <div class="form-group">
                   @Html.TextBoxFor(r => r.Name, new { @class = "form-control", @placeholder = "Name" })
                </div>
                <a href="#" class="btn btn-success btn-block" id="btnSubmit">Register</a>
            </div>
        </div>
    </form>
</div>  

@section scripts{
    <script>
        $(document).ready(function () {
            $('body').on('change', '#CustomerID', function () {
                var customerID = $(this).val();
                LoadCampaigns(customerID);
            })
        });

        function LoadCampaigns(customerID) {
            var $campaign = $('#CampaignID');

            $.ajax({
                url: '/Home/GetCampaignList',
                type: 'GET',
                data: { 'customerID': customerID },
                dataType: 'json',
                success: function (d) {
                    $campaign.empty();
                    $campaign.append($('<option></option>').val('').html("-- Select --"));
                    $.each(d, function (i, val) {
                        $state.append($('<option></option>').val(val.ID).html(val.Name));
                    });  
                }
            });
        }
    </script>
}

Thanks

Posted 13 days ago Modified on 12 days ago

Hi Herlan,

I have checked your code it is working at my end.

Refer below code.

Model

public class Campaign
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int CustomerID { get; set; }
}
public class Customer
{
    public int ID { get; set; }
    public string Name { get; set; }
}
public class CreateViewModel
{
    public int CustomerID { get; set; }
    public int CampaignID { get; set; }
    public int Name { get; set; }
}

Controller

public ActionResult Index()
{
    return View();
}
public ActionResult CreateRoom()
{
    TempData["CustomerList"] = new SelectList(GetCustomers(), "ID", "Name");
    TempData["CampaignList"] = new SelectList(new List<Campaign>(), "ID", "Name");
    return PartialView("CreateRoom");
}
public JsonResult GetCampaignList(int customerID)
{
    return new JsonResult { Data = GetCampaigns(customerID), JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
private List<Customer> GetCustomers()
{
    List<Customer> customers = new List<Customer>();
    customers.Add(new Customer { ID = 1, Name = "Customer 1" });
    customers.Add(new Customer { ID = 2, Name = "Customer 2" });
    return customers;
}
private List<Campaign> GetCampaigns(int customerID)
{
    List<Campaign> campaigns = new List<Campaign>();
    campaigns.Add(new Campaign { ID = 1, Name = "Camp 1", CustomerID = 1 });
    campaigns.Add(new Campaign { ID = 2, Name = "Camp 2", CustomerID = 2 });
    campaigns.Add(new Campaign { ID = 3, Name = "Camp 3", CustomerID = 2 });
    campaigns.Add(new Campaign { ID = 4, Name = "Camp 4", CustomerID = 1 });
    campaigns.Add(new Campaign { ID = 5, Name = "Camp 5", CustomerID = 2 });
    campaigns.Add(new Campaign { ID = 6, Name = "Camp 6", CustomerID = 1 });

    return campaigns.Where(x => x.CustomerID == customerID).ToList();
}

View

Index

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Index</title>
    <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>
</head>
<body>
    <div>
        <div class="row main-container">
            <div class="col-md-2">
                <div class="menu">
                    <a href="#" onclick="AddRooms()"><span class="glyphicon glyphicon-cog"></span>Crear
                        Sala</a>
                </div>
            </div>
        </div>
        <div class="modal" id="create-room" data-backdrop="static">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                            &times;</button>
                        <h4 class="modal-title">
                            New Room</h4>
                    </div>
                    <div class="modal-body" id="roomModalBody">
                    </div>
                </div>
            </div>
        </div>
        <script>
            var AddRooms = function () {
                $("#roomModalBody").load("/Home/CreateRoom", function () {
                    $("#create-room").modal("show");
                })
            }
        </script>
    </div>
</body>
</html>

CreateRoom

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>CreateRoom</title>
    <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>
        $(document).ready(function () {
            $('body').on('change', '#CustomerID', function () {
                var customerID = $(this).val();
                LoadCampaigns(customerID);
            })
        });

        function LoadCampaigns(customerID) {
            var $campaign = $('#CampaignID');
            $campaign.empty();
            $campaign.append($('<option></option>').val('').html('Please Wait..'));
            if (customerID == null || customerID == "") {
                $campaign.empty();
                $campaign.append($('<option></option>').val('').html('New Campaign'));
                return;
            }
            $.ajax({
                url: '/Home/GetCampaignList',
                type: 'GET',
                data: { 'customerID': customerID },
                dataType: 'json',
                success: function (d) {
                    $campaign.empty();
                    $campaign.append($('<option></option>').val('').html("-- Select --"));
                    $.each(d, function (i, val) {
                        $campaign.append($('<option></option>').val(val.ID).html(val.Name));
                    });
                },
                error: function (r) {
                    alert(r);
                }
            });
        }
    </script>
</head>
<body>
    <form id="formRegister">
    <div class="row">
        <div class="col-md-12">
            <%:Html.AntiForgeryToken() %>
            <div class="form-group">
                <%if (TempData["CustomerList"] != null)
                  { %>
                <%:Html.LabelFor(r => r.CustomerID)%>
                <%:Html.DropDownListFor(r => r.CustomerID, TempData["CustomerList"] as SelectList, "-- Select --", new { @class = "form-control" })%>
                <%}%>
            </div>
            <div class="form-group">
                <%:Html.LabelFor(r => r.CampaignID)%>
                <%:Html.DropDownListFor(r => r.CampaignID, TempData["CampaignList"] as SelectList, "-- Select --", new { @class = "form-control" })%>
            </div>
            <div class="form-group">
                <%:Html.LabelFor(r => r.Name)%>
                <%:Html.TextBoxFor(r => r.Name, new { @class = "form-control", @placeholder = "Name" })%>
            </div>
            <div class="form-group">
                <a href="#" class="btn btn-success btn-block" id="btnSubmit">Register</a>
            </div>
        </div>
        <div class="col-md-2">
        </div>
    </div>
    </form>
</body>
</html>

Screenshot