Click here to Skip to main content
15,879,490 members
Articles / Programming Languages / C#
Tip/Trick

Implementation of MVC3 Cascading Dropdown using jQuery

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
16 May 2013CPOL 22.7K   12  
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)

C#
[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)

C#
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)

C#
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:

C#
[HttpGet]

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

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

C#
@{ 
    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:

C#
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:

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

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

C#
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:

C#
@{ 

    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.

C#
public ActionResult getModule()

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

C#
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);
                      }
                  });
              }
        }
C#
var ArrProjMod = [];
$(document).ready(function () {
getModuel(null)
 });

Fill projectModule dropdown when project dropdown changes:

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

License

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


Written By
Technical Lead
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --