X

ASP MVC, Jquery modifying a select drop down with Json data

jquery

Was coding some new functionality and though I would post this, so that others can find it helpful.
Lets say you have a form that has a checkbox that will update the select dropdown box with different values, when the checkbox is clicked.
Something like the UI below.

Your html code might look like


Parent: 

Multiple: 

On your server side you would provide a Action Method to filter out the data, something like

[HttpGet]
        public JsonResult GetParents(int parentId, bool isMultiple)
        {
            //get from the database or something which is calling the possible parents 
            List result = GetPossibleParents(parentId, isMultiple);

            IDictionary dictionary = new Dictionary {{"-1", "None"}};

            foreach(ParentViewModel item in result)
            {
                dictionary.Add(item.Id.ToString(), item.Name);
            }

            return Json(dictionary, JsonRequestBehavior.AllowGet);
        }

Now we got to add the javascript to listen to the checkbox event changed, something like this in jquery, since we are getting Json Result we will have to parse the json object to populate the dropdown box.

 $('#fieldMultiple').live('change', function() {            
            var fieldId = $('#fieldId').val();
            var isMulti = false;    
            if ($(this).is(':checked')) {
                isMulti = true;                               
            }

            //call ajax now
                $ajax( {type: "POST", url: "someurl", data: { parentId: fieldId, isMultiple: isMulti},
                  success: function(data){
                         var dropDown = $('#fieldTypeDropDown');
                         //remove all the children
                         dropDown.children().remove();
                
                         //add the new children
                         $.each(data, function(key, value) {
                             dropDown.append('");
                          });
                
                          //create an effect to show its updated
                        dropDown.effect('shake', {times: 4}, 100);
                  }
                });
            }
         });

By doing so you will have something that shakes and updates the drop down box by some simple ajax calls 🙂

Categories: aspmvc JQuery
Taswar Bhatti:

View Comments (1)

Related Post