Home > OS >  How to create Cascading Dropdown
How to create Cascading Dropdown

Time:05-25

How to create Cascading Dropdown using Ajax Error Handling

Create dropdown Country State and District

1.When i click on on Country it show State.

2.When i click on State it Shows District.

public class Country
    {
        public int CountryId { get; set; }
        public string CountryName { get; set; }
    }

public class District
    {
        public int DistrictId { get; set; }
        public string DistrictName { get; set; }
    }

public class State
    {
        public int StateId { get; set; }
        public string StateName { get; set; }
    }

Controller

namespace Dropdown.Controllers
{
    public class CascadingController : Controller
    {
        private readonly DropdownContext _context;

        public CascadingController(DropdownContext context)
        {
            _context = context;
        }

        public IActionResult Index()
       {
            return View();
       }
       public IActionResult DropDown()
       {
            ViewBag.Country = _context.Country.ToList();
            ViewBag.District = _context.District.ToList();
            ViewBag.State = _context.State.ToList();
            return View();
       }
    }
}

this is my combine class

public class Combine
    {
        public int CombineId { get; set; }
        public int CountryId { get; set; }
        public int StateId { get; set; }
        public int DistrictId { get; set; }

        public Country Country { get; set; }
        public State State { get; set; }
        public District District { get; set; }
    }

View

this is View page i only add form html to show the dropdown i Does not add jQuery or something

@model Dropdown.Models.Combine
@{
    ViewData["Title"] = "DropDown";
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<html>
<head>
</head>
<body>
    <h1>DropDown</h1>
    <hr />

    <form>
        <div >
            <div >
                <div  style="padding-top: 8px;padding-right:7px;">
                    <label asp-for="Country" ></label>
                    <br />
                    <select asp-for="CountryId"  asp-items="@(new SelectList(ViewBag.Country,"CountryId","CountryName"))">
                    </select>
                </div>
                <br />

                <div  style="padding-top: 8px;padding-right:7px;">
                    <label asp-for="District" ></label>
                    <br />
                    <select asp-for="DistrictId"  asp-items="@(new MultiSelectList(ViewBag.District,"DistrictId","DistrictName"))">
                    </select>
                </div>
                <br />
                <div  style="padding-top: 8px;padding-right:7px;">
                    <label asp-for="State" ></label>
                    <br />
                    <select asp-for="StateId"  asp-items="@(new SelectList(ViewBag.State,"StateId","StateName"))">
                    </select>
                </div>

                <br />

                <input type="submit" value="Create"  />


            </div>
        </div>
    </form>

</body>
</html>


<br>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    <script><script type="text/javascript">
    </script>
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

enter image description here

Controller:

  public IActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public async Task<ActionResult> LoadCountry()
        {
            var country = ListOfCountry.ToList();
            
            return Ok(country);
           
        }

        [HttpGet]
        public async Task<ActionResult> GetState(int countryId)
        {
            var state = ListOfState.Where(cId => cId.CountryId == countryId).ToList() ;

            return Ok(state);

        }

        [HttpGet]
        public async Task<ActionResult> GetDistrict(int stateId)
        {
            var state = ListOfDistrict.Where(cId => cId.StateId == stateId).ToList();

            return Ok(state);

        }


    [HttpPost]
    public async Task<IActionResult> AddCountryStateDistrict(SubmitModel model)
    {
       
        return RedirectToAction("Index");
    }

Views:

        <div >
            <label >Country</label>
            <div >
                <select  id="ddlCountry"></select><br />
            </div>
        </div>

        <div >
            <label >State</label>
            <div >
                <select  id="ddlState"></select>
                <br />

            </div>
        </div>
        <br />
        <div >
            <label >District</label>
            <div >
                <select  id="ddlDistrict"></select>

            </div>
        </div>
           <div >
            <label ></label>
            <div >
                 <input id="Submit" value="Submit"  />

            </div>
        </div>
    </div>
    <div ></div>
   
   
</div>

Scripts:

@section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>

    $(document).ready(function () {

       var ddlCountry = $('#ddlCountry');
    ddlCountry.append($("<option></option>").val('').html('Please Select Country'));
    $.ajax({
        url: 'http://localhost:5094/CascadingDropdown/LoadCountry',
        type: 'GET',
        dataType: 'json',
        success: function (d) {
            console.log(d);
            $.each(d, function (i, country) {
                console.log(i);
                console.log(country);

                ddlCountry.append($("<option></option>").val(country.countryId).html(country.countryName));
            });
        },
        error: function () {
            alert('Error!');
        }
    });

    //State details by country id

    $("#ddlCountry").change(function () {

        //alert("On ddlCountry change");
        var CountryId = parseInt($(this).val());
        console.log(CountryId);
        if (!isNaN(CountryId)) {
            var ddlState = $('#ddlState');
            ddlState.empty();
            ddlState.append($("<option></option>").val('').html('Please wait ...'));


            $.ajax({
                url: 'http://localhost:5094/CascadingDropdown/GetState',
                type: 'GET',
                dataType: 'json',
                data: { CountryId: CountryId },
                success: function (d) {

                    ddlState.empty(); // Clear the please wait
                    ddlState.append($("<option></option>").val('').html('Select State'));
                    $.each(d, function (i, states) {
                        ddlState.append($("<option></option>").val(states.stateId).html(states.stateName));
                    });
                },
                error: function () {
                    alert('Error!');
                }
            });
        }


    });

    //District Bind By satate id
    $("#ddlState").change(function () {
        var StateId = parseInt($(this).val());
        if (!isNaN(StateId)) {
            var ddlDistrict = $('#ddlDistrict');
            ddlDistrict.append($("<option></option>").val('').html('Please wait ...'));
            $.ajax({
                url: 'http://localhost:5094/CascadingDropdown/GetDistrict',
                type: 'GET',
                dataType: 'json',
                data: { stateId: StateId },
                success: function (d) {


                    ddlDistrict.empty(); // Clear the plese wait
                    ddlDistrict.append($("<option></option>").val('').html('Select District Name'));
                    $.each(d, function (i, districts) {
                        ddlDistrict.append($("<option></option>").val(districts.districtId).html(districts.districtName));
                    });
                },
                error: function () {
                    alert('Error!');
                }
            });
        }


    });

    //On Submit Method
    
        $("#Submit").click(function(){
               var ddlCountry =  parseInt($("#ddlCountry").val());
               var ddlState =  parseInt( $("#ddlState").val());
               var ddlDistrict =  parseInt($("#ddlDistrict").val());
               
               var data = {
                ddlCountry: ddlCountry,
                ddlState: ddlState,
                ddlDistrict: ddlDistrict
                
            };
             console.log(data);
                  $.ajax({
                    url: 'http://localhost:5094/CascadingDropdown/AddCountryStateDistrict',
                    type: 'POST',
                    dataType: 'json',
                    data: data,
                    success: function (d) {
                       alert("Submitted To Database");
                    },
                    error: function () {
                        alert('Error!');
                    }
                });
                
        });

    });
</script>
        }

Output:

enter image description here

Hope this would guide you accordingly, what you are trying to achieve

  • Related