Thursday, August 30, 2012

Cascading Dropdowns in JcdcHelper

(Post by Lloyd Bates)
In this example, the parent Drop list is named "SepTypeCd" and the child is "SepReason".
When an item is selected in the parent the change event looks to see if a child list is required to be available, if a child menu is needed, it populates it, if not it disables the child dropdown control.
With this pattern, we get to use the Ajax Wrapper function to allow getting all the error handling built in as a bonus.
This example has the "if" statement in it, but it doesn’t have to have it.
 
        $(document).ready(function () {
           … …
            $(
"#SepTypeCd").change(SepTypeCdChange);
           … …
        });
 
       
function SepTypeCdChange() {
           
//Get selected item from parent drop list
           
var sepTypeCd = $('select[name=SepTypeCd] option:selected').val();
           
            
//Check if selected item should fire load of child drop.                                         
            
if ((sepTypeCd == "538") || (sepTypeCd == "540)
            {
               
//Set action url
               
var actionMethodUrl = '@Url.Action("GetSepReasonDD","StudentLookup")';
               
                
//make Ajax call to Get JSON, note: the param "Id" matches the param in the MethodAction.
                JcdcAjaxDoGetRetrieveJson(actionMethodUrl, GetDDLDataSuccess, {
"Id" : sepTypeCd } );
            }
           
else {
               
//If child is not to be used, clear options and disable it.
                $(
"#SepReasonCd").empty().end();
                $(
"#SepReasonCd").attr("disabled", "disabled");
            }
        }
       
//Success function can hold all your business logic for before and after drop list is loaded.
       
function GetDDLDataSuccess(jsonDDLDispValueCV) {
           
//Load all the options to the dropdown.
            LoadOptions(jsonDDLDispValueCV,
"SepReasonCd");
        }
       
//This function could be moved to JCDCAjax.js
       
function LoadOptions(jsonDDLDispValueCV, passedInSelectId) {
            
//clear old options from drop list
           
var reasons = $("#" + passedInSelectId).empty();
                       
            
//Load new items in drop list from Ajax data
            $.each(jsonDDLDispValueCV,
function(index, option) {
                reasons.append($(
'<option/>', { value: option.Value, text: option.Disp } ));
            });
           
//enable drop down
            reasons.removeAttr(
"disabled").end();
        }

No comments:

Post a Comment