Thursday, May 14, 2015

Kendo DropDownList triggering Select Event Programatically

I struggled trying to select an item in a Kendo dropdownlist programmatically and firing the corresponding select event.


Here's the solution.  Specifying .trigger("select") would fire the event, but the select function parameter "e" had no values.  To reconcile pass in the selected list item, using this syntax:
 dl.trigger("select", { item: $("li.k-state-selected", $("#dlTableNames-list")) }  











 @(Html.Kendo().DropDownListFor(model => model)  
        .DataSource(source =>  
        {  
          source.Read(read =>  
          {  
            read.Action("GetTableList", "Lists");  
          });  
        })  
        .DataTextField("DisplayName")  
        .DataValueField("id")  
             //.DataValueField("ANAPatternDesc")  
             //.SelectedIndex(0)  
        .Name("dlTableNames")  
        .OptionLabel("- Please select -")  
        .Events(e => {  
          e.Select("TableSelected");  
          // e.Change("TableSelected");  
          // e.Cascade("TableSelected");  
        })  
        .ValuePrimitive(true)  
        .HtmlAttributes(new { style = "width:400px" })  
        )  
 <script>  
 var dl = $("#dlTableNames").data("kendoDropDownList");  
 //Select an item by Value:  
 dl.value(5);  
           dl.trigger("select", { item: $("li.k-state-selected", $("#dlTableNames-list")) }  
 function TableSelected(e) {  
     var item = e.item;  
     //The display text (not value) of the selected drop down list item:  
     var text = item.text();  
     //Reference the kendo dropdownlist:  
     var dl = $("#dlTableNames").data("kendoDropDownList").dataSource;  
     var dataItem = this.dataItem(e.item.index());  
     //The id of the selected drop down list item:  
     var dataId = this.dataItem(e.item).id;  
     //Name used for parent div , also used for subdiv (prefixed with "subdiv"xxx):  
     var divid = text.replace(/\s+/g, '').replace(/\//g, '').replace(/\(/g, '').replace(/\)/g, '') + '_' + dataId;  
     //Create the parent level div, to which checkboxes will be added to via function => createCheckBox:  
     createSubElementDiv(divid, text);  
     //Remove the selected item from the dropdownlist, so the user won't have duplicates:  
     dl.remove(dl.at(e.item.index()));  
     //Via ajax, Get sublist of items and render to div as checkboxes:  
     var link = "@Url.Action("GetSubLists", "Lists", new { id = -1 })";  
     //Replace -1 with the id of the selected item, input parameter of the controller action method:  
     link = link.replace("-1", dataId);  
     $.ajax({  
       cache: false,  
       type: "GET",  
       dataType: "json",  
       contentType: "application/json; carset=utf-8",  
       url: link,  
       data: { "id": text },  
       success: function (data) {  
         name = data;  
         // For each line in json object, create a checkbox:  
         $.each(data, function (key, value) {  
           createCheckBox('subdiv' + divid, value.id, value.Text);  
         });  
       },  
       error: function (xhr, ajaxOptions, thrownError) {  
         customMsg('An error occurred loading data. The Administrator has been notified.' + thrownError);  
       }  
     });  
     //Collapse the drop down list:  
     $("#dlTableNames").data("kendoDropDownList").close();  
     return false;  
   }  
 </script>  

Tuesday, May 12, 2015

Using a Kendo Window like a javascript prompt to get input

Create the following div:



 <div id="inputWindow">  
   <label for="userinput">Save Search as Name:</label>  
   <input type="text" name="userinput" id="userinput" title="Search Name" />  
 </div>  

Call showSaveAsDialog()

If the user does not enter a value in the textbox, the function exits.  If they do and close the popup window, the function continues, writing data to the controller via ajax:


 var saveName = '';  
   var handleUserInput = function () {  
     var userinput = ($("#userinput").val());  
     if (userinput.length == 0) {  
       alert('A name for the saved filter is required.');  
       return;  
     }  
     else {  
       saveName = userinput;  
       //  
       var list = [];//The final output list  
       $('.formFieldWrapper').each(function () {  
         //get the id of the parent DIV containter:  
         var parentid = this.id;  
         var index = parentid.lastIndexOf("_");  
         //Get the ID for the parent as stored in db table TableList  
         var FilterTableID = parentid.substr(index + 1);  
         //Foreach checkbox checked in this parent:  
         $('#' + parentid + ' input:checked').each(function () {  
           //Populate Object Literal with the uid of the selected table ( into FilterTableID),  
           list.push({ id: this.id.replace('ck', ''), FilterTableID: FilterTableID });  
         });  
       });  
       var userid = "@User.Identity.GetUserId()";  
     var url = "@Url.Action("SaveFilter", "SaveFilter", new { id = -1 , SavedName = -2, jsonData = -3 })";  
       //Replace -1 with the id of the selected item, input parameter of the controller action method:  
       url = url.replace("-1", userid);  
       url = url.replace("-2", saveName);  
       url = url.replace("-3", $.toJSON(list));  
       $.ajax({  
         cache: false,  
         type: "POST",  
         dataType: "html",  
         contentType: "application/json; carset=utf-8",  
         url: url,  
         success: function (data) {  
           alert('saved');  
         },  
         error: function (xhr, ajaxOptions, thrownError) {  
           customMsg(' Save Search', 'Oh Oh, An error occurred while attempting to save your search. The Administrator has been notified.' + thrownError);  
         }  
       });  
     }  
   }  
   function showSaveAsDialog() {  
     var win = $("#inputWindow")  
   .kendoWindow({  
     actions: ["Maximize", "Close"],  
     animation: {  
       open: {  
         effects: "slideIn:down fadeIn",  
         duration: 500  
       },  
       close: {  
         effects: "slide:up fadeOut",  
         duration: 500  
       }  
     },  
     minWidth: 300,  
     modal: true,  
     resizable: true,  
     title: "Name to save the Filter As",  
     visible: false,  
     close: handleUserInput  
   })  
   .data("kendoWindow")  
   .center();  
     var wrapper = win.wrapper;  
     wrapper.css({ top: 25 });  
     win.open();  
   }  

Friday, May 8, 2015

Kendoh Dropdownlist value undefined!

I tried for hours to get the value from a kendo dropdownlist, to no avail.  It was driving me nuts.
It has a method calld .value() - that didn't work, dataItem.value did not work either.


Finaaly out of desperation, I realized that I had the data item, and thought, perhaps it contains the field names, just like the json delivered to it.  The solution was simply to specify dataItem.xxx where xxx is the name of the field I wanted to the value from.  Here's the code example:


  @(Html.Kendo().DropDownListFor(model => model)  
 .DataSource(source =>  
 {  
   source.Read(read =>  
     {  
       read.Action("GetTableList", "Lists");  
     });  
 })  
 .DataTextField("DisplayName")  
 .DataValueField("id")  
     //.DataValueField("ANAPatternDesc")  
     //.SelectedIndex(0)  
 .Name("dlTableNames")  
 .OptionLabel("- Please select -")  
 .Events(e => e.Select("TableSelected"))  
 .ValuePrimitive(true)  
  .HtmlAttributes(new { style="width:400px" })  
 )  

JavaScript to get the value:



  function TableSelected(e) {  
    var item = e.item;  
    var text = item.text();  
    var dl = $("#dlTableNames").data("kendoDropDownList").dataSource;  
    var dataItem = this.dataItem(e.item);  
    //alert($("#dlTableNames").getKendoDropDownList().dataSource.data().length);  
    alert(dataItem.id);  

Note the commented line, this feature is cool, if the drop downlist is not data bound it will return an empty array, otherwise it will return an array of itesm