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

Tuesday, March 31, 2015

Cool Stuff, Editable Grid with Automatic Changes saved

This is ideal for checkboxes.  Placing a grid in .Batch(true) and .ServerOperation(false) allows the user to click on a cell to edit it's value.  Usually there is a "Save Changes" button they have to click to save all their changes.

In this solution we allow users to check or uncheck checkboxes - when they change the state of a checkbox, it updates the database automatically - no need to have the user click the save changes button.

Create a template column:

  c.Bound("ArticleIsMine").ClientTemplate("<input type='checkbox' #= ArticleIsMine? checked='checked': checked='' # class='chkbx' />");  

Add a change event to the grid's datasource:
  .DataSource(data => data.Ajax()  
      .Model( m =>  
    {  
      m.Id("Id");  
      m.Field(f => f.PubDate).Editable(false);  
      m.Field(f => f.Title).Editable(false);  
    })  
    .Events(e => e.Change("dataChange"))  

Add the JavaScript event and code for the template checkbox:
 $(document).ready(function () {  
     kendo.data.DataSource.prototype.options.autoSync = true;  
     $('#gvPubs').on('click', '.chkbx', function () {  
       var checked = $(this).is(':checked');  
       var g = $('#gvPubs').data().kendoGrid;  
       g.closeCell();  
       var dataItem = g.dataItem($(this).closest('tr'));  
       var col = $(this).closest('td');  
       g.editCell(col);  
       dataItem.set(g.columns[col.index()].field, checked);  
       g.closeCell(col);  
     });  
the sync call does the actual save:
  function dataChange(e) {  
     if (e.action == "itemchange") {  
       this.sync();  
     }  
   }  

The checkbox javascript code updates the in memory model with the new value of the control, the dataChange function saves the changes to the database (calls the grid's Update method).

BTW, the code formatting for this blog post was done using this handy tool:
http://codeformatter.blogspot.com/

Monday, March 30, 2015

How to make a Kendo UI Grid cell non-editable:

How to make a Kendo UI Grid cell non-editable:

In the data source, make the field editable(false):

.DataSource(data => data.Ajax() .Model(
m => { m.Id("Id");
m.Field(f => f.PubDate).Editable(false);
m.Field(f => f.Title).Editable(false); })

Wednesday, March 4, 2015

Cancel/Close the Grid Popup Editor Window

I had a requirement that if a condition was met, when a user clicked Add New Record, it would close the popup window, and display a message instead, accomplished with js like this:

function editmode(e) {
        if (e.model.isNew()) {
            var target = $("#cathTestDate").data("kendoDropDownList");
            var len = target.dataSource.data().length;
            e.preventDefault();
            this.editRow($(e.currentTarget).closest("tr"));
            alert(len);
        }
    }

 Declare in the grid:

@(Html.Kendo().Grid<Model.Models.CathReport>()
            .Name("cathreportgrid")
            .Events(e => {
                e.Edit("editmode");
            })

Wednesday, February 25, 2015

Grid Popup Editing Template, show/hide field based on another bit field.

We have a grid that used a template editor for poup editing.
We have a bool field that if clicked, we want to show the corresponding value field, otherwise, hide it.

I gave the div that I want to hide/show an ID and set it's visibility to hidden (the first editor is the bool field):
<div>
            <div class="editor-label">
                <b>Right Ventricular Hypertrophy?</b>
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.IsRightVentHypertrophy)
                @Html.ValidationMessageFor(model => model.IsRightVentHypertrophy)
            </div>
        </div>
        <div id="RVentFuncDiv"  style="visibility: hidden; z-index: 9999;">
            <div class="editor-label">
                <b>Right Ventricular Function:</b>
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.fk_RightVentricularFunctionID, "RVFunction")
                @Html.ValidationMessageFor(model => model.fk_RightVentricularFunctionID)
            </div>
        </div>

I created the following js function on the editor template:

 function checkit(parent, child) {
        if ($("#" + parent).is(':checked'))
            $("#" + child).css("visibility", "visible");
        else
            $("#" + child).css("visibility", "hidden");
    }

and called it on it's document.ready:

$(document).ready(function () {
  $("#IsRightVentHypertrophy").change(function () {
            checkit("IsRightVentHypertrophy", "RVentFuncDiv");
        });
    });


Back on the main page the grid was assigned an event for edit:

.Name("echogrid")
.Events(e =>
    {
        e.Edit("editmode");
    })

An here is the js function for that event:
   function editmode(e) {
        checkit("IsRightVentHypertrophy", "RVentFuncDiv");
    }