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");
    }


Monday, February 16, 2015

Lousy built in Exporting

the 2014 3rd quarter release of Kendo grid has export capability via commands, it sucks.
Because, instead of exporting the data as displayed in the grid, it will export the underlying values instead.  If you use templates that is:
"Yes, by design the data from the data source is exported. If a grid column has its template set it will be ignored. Templates can be arbitrary HTML which doesn't translate to Excel. If the template isn't HTML you can manually use it as shown in this help article: http://docs.telerik.com/kendo-ui/web/grid/how-to/excel/column-template-export
"

If you are not using templates then you might find this article useful:
http://developer.telerik.com/featured/exporting-data-ease-using-kendo-ui-grid/

Friday, December 26, 2014

DropDown Displaying Json Date in DataTextField

I had a foreign key kendo drop down list editor template, and the DataTextField was pointed to a DateTime field, it was displaying items in the dropdown in the following json format:

/Date(1124859600000)/

The solution to display it as a simple date was to utilize templates using Kendo Format:

@using Kendo.Mvc.UI
@model IQueryable<Model.Models.OfficeVisit>
@{var val = string.Empty;
  if (Request.QueryString["id"] != null)
  {
      val = Request.QueryString["id"];
  }
  else
  {
      //No Querystring, so use the id from action call:
      val = Url.RequestContext.RouteData.Values["id"].ToString();
  }
}
@{
    Layout = null;
}
<script>
    function GetValue() {
        return {
            Id: "@val"
        };
    }
</script>
@(Html.Kendo().DropDownList()
.DataSource(source =>
{
    source.Read(read =>
        {
            read.Action("GetPatientOfficeVisits", "OfficeVisits").Data("GetValue()");
        });
})
.DataTextField("VisitDate")
.TemplateId("dltemplate")
.ValueTemplateId("dltemplate")
.DataValueField("pk_OfficeVisitID")
        //.DataValueField("ANAPatternDesc")
        //.SelectedIndex(0)
.Name("fk_OfficeVisitID")
.OptionLabel("- Please select -")
 .HtmlAttributes(new { data_value_primitive = true })
)
<script type="text/x-kendo-template" id="dltemplate">
    #:kendo.toString(kendo.parseDate(data.VisitDate), 'MM/dd/yyyy')  #
</script>

Monday, December 15, 2014

How to update an EditorFor that uses a kendo NumericTextBoxFor control.

Easy to get a value using .val(), but to set the value you have to call the change event of the control and navigate away from it in order to save the changes to the model!

 @Html.EditorFor(model => model.PVR, "Number")

Here's the editorTemplate named "Number":

@model double?
@using Kendo.Mvc.UI
@(Html.Kendo().NumericTextBoxFor(m => m)
.Decimals(3)
.Format("0.000")
      .HtmlAttributes(new { style = "width:100%" })
)


here's the jscript code to update the value:

var kendo = $("#PVR").data("kendoNumericTextBox");
            kendo.value(output);
            kendo.trigger("change");
            var target = $("#Wedge").data("kendoNumericTextBox");
            target.siblings("input:visible").focus();