65.9K
CodeProject is changing. Read more.
Home

Implementation of MVC3 Cascading Dropdown using jQuery

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

May 16, 2013

CPOL
viewsIcon

22921

Load child dropdown without hitting the database in MVC3 using jQuery

Introduction

Requirement: In pageload, I need to fill Project Dropdown List. On change of the Project Dropdown, ProjectModule dropdown needs to fill without hitting the database every time.

Table Structure

ProjectMaster(DB Model)

   [Table(Name = "ProjectMaster")]

    public class ProjectMaster
    {
        [Column(Name="ID", IsDbGenerated=true, IsPrimaryKey=true )]
        public int ID { get; set; }

        [Column(Name = "Project")]
        public string Project { get; set; }

        [Column(Name = "Description")]
        public string Description { get; set; }

        [Column(Name = "Active")]
        public bool Active { get; set; }

    }

ProjectModule (DB Model)

 public class ProjectModule
    {
        [Column (Name="ID", IsDbGenerated=true, IsPrimaryKey=true)]
        public int ID { get; set; }

        [Column(Name = "ProjectMaster_Id")]
        public int ProjectMaster_Id { get; set; }

        [Column(Name = "Description")]
        public string Description { get; set; }

        [Column(Name = "Active")]
        public bool Active { get; set; }
  
    }

ProjectModuleDTO (Model)

public class ModProjDTO
    {
        public int ModId { get; set; }
        public string ModName { get; set; }
        public int ProjId { get; set; }
        public bool IsActive { get; set; }
        public string ProjName { get; set; }
    }

Step 1: Fill Project dropdown list

In Controller:

 [HttpGet]       

 public ActionResult Index()
  {
      ViewData["ProjectList"] = IdbAct.getProjectList(ref errorMsg);            
      return View();    
        }

Note: ‘IdbAct.getProjectList’ returns ProjectList In View (.cshtml)

@{ 
    ViewBag.Title = "Index";
    IEnumerable<ProjectMaster> objProjList = (IEnumerable<ProjectMaster>)ViewData["ProjectList"];
    SelectList projList = new SelectList(objProjList, "ID", "Project");
 }

<td width ="25%"> @Html.Label("Project") </td>      

     <td width ="25%"> @Html.DropDownListFor(Model => 
     Model.ProjectMaster_Id, projList, "-Select One-", 
     new { id = "ddlProject" }) </td> 

This fills our ProjectDropdown list. So far so good!!!!Step 2: Fill ProjectModule dropdown list Our next step is to load project module for a selected project: Here we need projectmodule with projectId. Our Dataset structure would be as below:

public class ModProjDTO
    {
        public int ModId { get; set; }
        public string ModName { get; set; }
        public int ProjId { get; set; }
        public bool IsActive { get; set; }
        public string ProjName { get; set; }
    }

So, who do we load ModProjDTO from database, we have many option.
My approach is here - as below.

In Controller:

 [HttpPost]
 public ActionResult getModue()
 {           
    return Json(IdbAct.getModuleList(ref errorMsg),JsonRequestBehavior.AllowGet);
 }

Let’s have a look at the ‘IdbAct.getModuleList’ method:

 
 return (from projMod in objDbCon.GetTable<ProjectModule>()

         join prj in objDbCon.GetTable<ProjectMaster>()
         on projMod.ProjectMaster_Id equals prj.ID
         select new ModProjDTO
                {
                  ModId =  projMod.ID,
                  ModName = projMod.Description,
                  ProjId = projMod.ProjectMaster_Id,
                  IsActive = projMod.Active,
                   ProjName = prj.Project 
                }); 

This returns IEnumerable<ModProjDTO>Adding project module dropdown list in view:

@{ 

    SelectList projModuleList = new SelectList("ProjectModule_Id", "");
 } 

<td width ="25%"> @Html.Label("Project Module") </td>    

<td> @Html.DropDownListFor(Model => Model.ProjectModule_Id, projModuleList, 
"-Select One-", new { id = "ddlModule" }) </td>   

Now we need to access: getModule() i.e.

public ActionResult getModule()

Here I’m making an Ajax Call to fetch all projectModule details.

  function getModuel(id) {

            $("#ddlModule").html("");  

                if (id == null) {                   
                    $.ajax({
                        url: "IT/getModue",
                        dataType: "json",
                        type: "POST",
                        error: function () {
                            alert(" An error occurred.");
                        },
                        success: function (data) {
                            $.each(data, function (i) {                                 
                                ArrProjMod.push(data[i]);
                            });                            
                        }
                    });                    
                }
                else {             
                    $.each(ArrProjMod, function (i, obj) {
                        if (id == obj.ProjId) {
                            var optionhtml = '<option value="' + 
                            obj.ModId + '">' + obj.ModName + '</option>';
                            $("#ddlModule").append(optionhtml);
                        }                        
                    });                              
                }
          }
 var ArrProjMod = [];
 $(document).ready(function () {                
 getModuel(null)         
  });

Fill projectModule dropdown when project dropdown changes:

 $('#ddlProject').change(function () {
            var projId = $("#ddlProject").val();               
            getModuel(projId);
        });