Cascading (Dependent) DropDownList using ASP.Net MVC

Chevy Mark Sunderland 61 Reputation points
2021-01-02T20:08:18.563+00:00

Hi,

I have implemented Cascading (Dependent) DropDownList using ASP.Net MVC.

Now I need show alert message box after insert data and redirect on Index page in ASP.Net MVC.

To show alert message in asp.net mvc after insert data using store procedure from MySQL database, I have write the code like as shown below.

The data is correctly registered in the database table and the alert message box after insert data it's show.

But the redirect to index.cshtml not working because all the DropDownList on the form are empty except the first DropDownList that populates correctly.

window.location.href = "@Url.Action("Index", "Home")";

I mean that all other (populated cascading) DropDownList are enabled but empty.

I need redirect to Index Action page and being able to reload a new record, with this redirection it is impossible because the populated cascading DropDownList remain empty... instead of disabled and populated from value of first dropdownlist...

After insert data if change value on the first dropdownlist all other dropdownlist are not populated, I need close webpage and restart debug on VS 2019, for insert new record.

How to do resolve this?

Thanks.

Controller

    [HttpPost]
    public ActionResult Index(PersonModel person, string countryId, string stateId)
    {                
        MTsqlinsert(person); //Insert values in the database

        if (ModelState.IsValid)
        {
            PersonModel personModel = new PersonModel();

            person.Countries = PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId");
            person.States = PopulateDropDown("SELECT StateId, StateName FROM States WHERE CountryId = '" + countryId, "StateName", "StateId");
            person.Cities = PopulateDropDown("SELECT CityId, CityName FROM Cities WHERE StateId = '" + stateId, "CityName", "CityID");

            ViewData["result"] = "1";
            return RedirectToAction("Index");
        }
        return View(person);
    }

    [HttpGet]
    [OutputCache(NoStore = true, Duration = 60, VaryByParam = "*")]
    public ActionResult Index()
    {
        PersonModel personModel = new PersonModel
        {
           Countries = PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId");
        };

        return View(personModel);
    }
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,252 questions
{count} votes

Accepted answer
  1. Yihui Sun-MSFT 801 Reputation points
    2021-01-04T05:41:35.743+00:00

    Hi @Chevy Mark Sunderland ,

    1. Do you want the second and third drop-down lists to initially display different options based on the selection in the previous drop-down list?
    2. At the same time, when you submit the form, do you want to return to the view with the data you previously selected instead of the default initial value?
    3. If this is the case, you can refer to the following example.

    Model

        public class PersonModel  
        {  
            public string CountryId { get; set; }  
            public string StateId { get; set; }  
            public string CityId { get; set; }  
            public SelectList Countries { get; set; }  
            public SelectList States { get; set; }  
            public SelectList Cities { get; set; }  
        }  
        public class Country  
        {  
            [Key]  
            public int CountryId { get; set; }  
            public string CountryName { get; set; }  
        }  
        public class State  
        {  
            [Key]  
            public int StateId { get; set; }  
            public string StateName { get; set; }  
            public int CountryId { get; set; }  
            [ForeignKey("CountryId")]  
            public Country Country { get; set; }  
        }  
        public class City  
        {  
            [Key]  
            public int CityId { get; set; }  
            public string CityName { get; set; }  
            public int StateId { get; set; }  
            [ForeignKey("StateId")]  
            public State State{ get; set; }  
        }  
    

    Controller

        public class CascadingDropDownListController : Controller  
        {  
            public DailyMVCDemoContext db = new DailyMVCDemoContext();  
            public ActionResult Index(int? defaultCountryId = 1)  
            {  
                PersonModel model = new PersonModel();  
                //get all country  
                var allCountrylist = db.Countrys.ToList();  
                //get all states according to defaultCountryId  
                var allStatelist = db.States.Where(m => m.CountryId == defaultCountryId).ToList();  
                //set defaultStateId  
                var defaultStateId = allStatelist.Select(m => m.StateId).FirstOrDefault();  
                //Get all cities according to defaultStateId  
                var allCitylist = db.Citys.Where(m => m.StateId == defaultStateId).ToList();  
                //set defaultCityId   
                var defaultCityId = allCitylist.Select(m => m.CityId).FirstOrDefault();  
                model.Countries = new SelectList(allCountrylist, "CountryId", "CountryName", defaultCountryId);  
                model.States = new SelectList(allStatelist, "StateId", "StateName", defaultStateId);  
                model.Cities = new SelectList(allCitylist, "CityId", "CityName", defaultCityId);  
                return View(model);  
            }  
            [HttpPost]  
            public JsonResult setDropDrownList(string type, int value)  
            {  
                PersonModel model = new PersonModel();  
                switch (type)  
                {  
                    case "CountryId":  
                        var statesList = db.States.Where(m => m.CountryId == value).ToList();  
                        model.States = new SelectList(statesList, "StateId", "StateName");  
                        var defaultStateId = statesList.Select(m => m.StateId).FirstOrDefault();  
                        model.Cities = new SelectList(db.Citys.Where(m => m.StateId == defaultStateId).ToList(), "CityId", "CityName");  
                        break;  
                    case "StateId":  
                        model.Cities = new SelectList(db.Citys.Where(m => m.StateId == value).ToList(), "CityId", "CityName");  
                        break;  
                }  
                return Json(model);  
            }  
            [HttpPost]  
            public ActionResult Index(PersonModel model)  
            {  
                model.Countries = new SelectList(db.Countrys.ToList(), "CountryId", "CountryName", model.CountryId);  
                model.States = new SelectList(db.States.Where(m => m.CountryId.ToString() == model.CountryId).ToList(), "StateId", "StateName", model.StateId);  
                model.Cities = new SelectList(db.Citys.Where(m => m.StateId.ToString() == model.StateId).ToList(), "CityId", "CityName", model.CityId);  
                return View(model);  
            }  
        }  
    

    View

    @model DailyMVCDemo2.Models.PersonModel  
    <div id="dropDownListdiv">  
        @using (Html.BeginForm("Index", "CascadingDropDownList", FormMethod.Post))  
        {  
            @Html.DropDownListFor(m => m.CountryId, Model.Countries, "Please select", new { @class = "form-control" })  
            @Html.DropDownListFor(m => m.StateId, Model.States, "Please select", new { @class = "form-control" })  
            @Html.DropDownListFor(m => m.CityId, Model.Cities, "Please select", new { @class = "form-control" })  
            <input type="submit" value="Submit" />  
        }  
    </div>  
    

    JavaScript Code on View

                $(function () {  
                    $("#dropDownListdiv").on("change", "select", function () {  
                          var value = $(this).val();  
                          var id = $(this).attr("id");  
                          $.post("@Url.Action("setDropDrownList")", { type: id, value: value }, function (data) {  
                                switch (id) {  
                                        case "CountryId":  
                                            PopulateDropDown("#StateId", data.States);  
                                            PopulateDropDown("#CityId", data.Cities);  
                                            break;  
                                        case "StateId":  
                                            PopulateDropDown("#CityId", data.Cities);  
                                            break;  
                                 }  
                        });  
                    });  
                });  
                function PopulateDropDown(dropDownId, list) {  
                    $(dropDownId).empty();  
                    $(dropDownId).append("<option>Please select</option>")  
                    $.each(list, function (index, row) {  
                        if (index == 0) {  
                            $(dropDownId).append("<option value='" + row.Value + "' selected='selected'>" + row.Text + "</option>");  
                        } else {  
                            $(dropDownId).append("<option value='" + row.Value + "'>" + row.Text + "</option>")  
                        }  
                    });  
                }  
    

    53126-result.gif


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
    Best Regards,
    YihuiSun


1 additional answer

Sort by: Most helpful
  1. Lg 1 Reputation point
    2021-10-20T13:10:40.04+00:00

    What does DailyMVCDemoContext represent? In the controller?