Click here to Skip to main content
15,039,470 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
hi i have two dropdownlist on a page i want that when i select some value from first dropdown list then in second dropdownlist all the values load according to the value selected
both dropdown lists are binded dynamically

View
First Dropdown
C#
@Html.DropDownList("Departments",dept,"--Select Department--",new { @required="required" })

Second Dropdown
C#
@Html.DropDownList("Physician", phy, "--Select Physician--", new { @required="required" })


Function to Bind values
C#
public List<SelectListItem> Departments()
        {
            List<SelectListItem> dept = new List<SelectListItem>();
            var query = from u in db.Departments select u;
            if (query.Count() > 0)
            {
                foreach (var v in query)
                {
                    dept.Add(new SelectListItem { Text = v.Name, Value = v.ID.ToString() });
                }
            }
            return dept;
        }


C#
public List<SelectListItem> Physicians()
        {
            List<SelectListItem> phy = new List<SelectListItem>();
            var query = from u in db.Physicians select u;
            if (query.Count() > 0)
            {
                foreach (var v in query)
                {
                    phy.Add(new SelectListItem { Text = v.FirstName + " " + v.LastName, Value = v.ID.ToString() });
                }
            }
            return phy;
        }
Posted
Updated 30-Jan-18 5:44am

JavaScript

JavaScript
<script type="text/javascript">
     $(document).ready(function () {
         $("#departmentList").change(function () {
             var dID= $(this).val();             
             $.getJSON("../Home/LoadPhysiansByDepartment", { deptId: dID },
                    function (data) {
                        var select = $("#physiciansList");
                        select.empty();
                        select.append($('<option/>', {
                            value: 0,
                            text: "Select a Physian"
                        }));
                        $.each(data, function (index, itemData) {
                            select.append($('<option/>', {
                                value: itemData.Value,
                                text: itemData.Text
                            }));
                        });
                    });
         });
});



In View You Write
C#
@Html.DropDownListFor(Model => Model.Departments, new SelectList(ViewBag.Departments as System.Collections.IEnumerable, "ID", "Name"),

            "Select a Student", new { id = "departmentList" })
        
        <p>
            @Html.DropDownListFor(Model => Model.Physicans, new SelectList(Enumerable.Empty<SelectListItem>(), "phyID", "phyName"),
            "Select a Physican", new { id = "physiciansList" })
        </p>


And In Controller

C#
public ActionResult Index()
{
List<SelectListItem> dept = new List<SelectListItem>();
            var query = from u in db.Departments select u;
            if (query.Count() > 0)
            {
                foreach (var v in query)
                {
                    dept.Add(new SelectListItem { Text = v.Name, Value = v.ID.ToString() });
                }
            }
            ViewBag.Departments = dept;
return View();
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult LoadPhysiansByDepartment(string deptId)
{
//Your Code For Getting Physicans Goes Here
   var phyList = this.GetPhysicans(Convert.ToInt32(deptId));


   var phyData = classesList.Select(m => new SelectListItem()
    {
       Text = m.phyName,
       Value = m.phyId.ToString(),
    });
       return Json(phyData , JsonRequestBehavior.AllowGet);
}



syntax may be not correct because currently i have no visual studio but the idea is correct you can correct syntax in your side
   
Comments
Member 11282084 23-Dec-14 5:35am
   
Can you please tell me how to hide some textbox on dropdown selectedindexchange event in mvc5
Heba Kamel 5-Nov-15 8:15am
   
Hi,
Thank you for this solution
but how get selected value in contoller to save it ?
thanks
Nobert Paa Qwame Mensah 14-Mar-16 5:29am
   
works for me Thank you so much
This site helped me a lot, so i am giving back something. cheers ! This code works without any error.Thanks
JavaScript
HTML
<pre>    <script type="text/javascript">
     $(document).ready(function () {
         $("#Typeid").change(function () {
             var dID = $('#Typeid option:selected').val();
             $.getJSON("../Manage/GETSubType", { Typeid: dID },
                    function (data) {
                        var select = $("#subtypeid");
                        select.empty();
                        select.append($('<option/>', {
                            value: 0,
                            text: "Select project sub-types"
                        }));
                        $.each(data, function (index, itemData) {
                            select.append($('<option/>', {
                                value: itemData.Value,
                                text: itemData.Text
                            }));
                        });
                    });
         });
});

        </script>

Controller
C#
[AcceptVerbs(HttpVerbs.Get)]
    public JsonResult GETSubType(string Typeid)
    {

        dbproject = new DbProject();


          return Json(dbproject.ProjectType_SubTypeList(Convert.ToDouble( Typeid)), JsonRequestBehavior.AllowGet);

    }

Method in class
C#
<pre>  public List<SelectListItem> ProjectType_SubTypeList(double id)
        {
            var subtypes = from u in db.SubType where u.ProjectTypeID==id.ToString()  select u;
            List<SelectListItem> ProjectsubTypes = new List<SelectListItem>();
            ProjectsubTypes.Clear();
         //   ProjectsubTypes.Add(new SelectListItem { Text = "--Select Project sub-Type--", Value = "0" });
            if (subtypes!=null)
            {
                foreach(var subtype in subtypes)
                {
                    ProjectsubTypes.Add(new SelectListItem { Text = subtype.name, Value = subtype.id.ToString() });
                }
            }
            return ProjectsubTypes;
        }

HTML
View
<pre> <div class="form-group">
                        <div class="form-group col-md-6 col-sm-6 col-xs-12 has-feedback">
                            @Html.DropDownListFor(model => model.Project.ProjectType, new SelectList(ViewBag.Type as System.Collections.IEnumerable, "Value", "Text"), new { @class = "form-control", @id = "Typeid" })
                            @Html.ValidationMessageFor(model => model.Project.ProjectType, "", new { @class = "text-danger" })
                        </div>
                  <div class="form-group col-md-6 col-sm-6 col-xs-12 has-feedback">
                            @Html.DropDownListFor(model => model.Project.SubProjectID, new SelectList(Enumerable.Empty<SelectListItem>(), "id", "name"),
                            "Select project sub-types", new { @class = "form-control", @id = "subtypeid" })
                            @Html.ValidationMessageFor(model => model.Project.SubProjectID, "", new { @class = "text-danger" })
                        </div>
                    </div>
   
Comments
Member 13663829 14-Oct-20 7:57am
   
it give me load of error

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900