Image in Kendo Grid Dropdown List

In this article, I would demonstrate how to insert a image in dropdown list (inside kendo grid) based on Type (CrewId) also this will help us to how to define the foreign key column in kendo grid

In this example, the grid will contain 3 columns a) Id b) CrewId [Man/Machine which is foreign key column] 3) Comments

Let’s define below Kendo Grid in Index.cshtml of HomeController. This is a basic kendo grid configuration with 2 columns as Bound columns

and another column as ForeignKey Column which contains CrewID and we have list of CreworEquipment data which is stored in ViewState.


@(Html.Kendo().Grid<UserMachine>()
.Name("MyGrid")
.HtmlAttributes(new { style = "height:100%; width:100%; " })
.Columns(columns =>
{
columns.Bound(m => m.Id).Hidden(true);
columns.ForeignKey(m => m.CrewId, (System.Collections.IEnumerable)ViewData["CrewOrEquipment"], "Id", "Name").Title("User/Equipment").Width(100);
columns.Bound(m => m.Comments).Width(175).Title("Comments");
}
)
.ToolBar(toolbar => toolbar.Template(
<text>
<a class="k-button k-button-icontext k-grid-add anch-show-hide"><span class="k-icon k-add"></span></a>
<a class="k-button k-button-icontext anch-show-hide" id="cancelAct1" href="javascript:void(0)"><span class="k-icon k-cancel"></span></a>
</text>))
.Scrollable()
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Filterable()
.Sortable()
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(false)
.Model(model =>
{
model.Id(row => row.Id);
}
)
.ServerOperation(false)
.PageSize(25)
)
.Resizable(resize => resize.Columns(true))
.Selectable(selectable => selectable.Mode(GridSelectionMode.Multiple))

The major part of the code is the Grid Foreign Key template which would be defined in Shared folder. Lets add file GridForeignKey.cshtml inside folder View ==> Shared ==> EditorTemplate and add the below code to the file.


@(Html.Kendo().DropDownListFor(m => m).DataValueField("Id").DataTextField("Name")
.BindTo((System.Collections.IEnumerable)ViewData["CrewOrEquipment"])
.TemplateId("contact-template"))

Now lets define below template, and this is pretty straightforward based on Id, we are setting the respective Image along with data to it.

 
<script id="contact-template" type="text/x-kendo-template"> 
# if(data.CrewType == 1) { # 
 <img alt="icon" class="k-image" src="http://icons.iconarchive.com/icons/icons-land/vista-people/16/Office-Customer-Male-Light-icon.png"> #: data.Name # 
# } # 

# if(data.CrewType == 2) { # 
 <img alt="icon" class="k-image" src="http://icons.iconarchive.com/icons/iconshock/real-vista-construction/16/hand-driller-icon.png"> #: data.Name # 
# } # 

</script> 

Finally lets define the Controller action Index with following code. As you can see we are using the ViewData in our ForeignKey column

public ActionResult Index()
{
    ViewData["CrewOrEquipment"] = GetCrewOrEquipment();
    return View();
}

Let’s run the application and once page loads, click the Plus button and now you select Crew Columns and you should be seeing the Images (crew/equipment images) based on type.

Hope this was helpful…

Removing a Row from KENDO GRID

In this article, will demonstrate how to remove multiple grid items when a button is clicked.

Below is basic grid configuration.



@(Html.Kendo().Grid<User>()
           .Name("UserGrid")
            .HtmlAttributes(new { style = "height:100%; width:100%; " })
            .Columns(columns =>
            {
                       columns.Bound(m => m.Id).Hidden(true);
                       columns.Bound(m => m.Name).Width(175).Title("Name");
                       columns.Bound(m => m.Hours).Width(175).Title("Hrs");
                       columns.Bound(m => m.Comments).Width(175).Title("Comments");
            }
            )
            .Scrollable()
            .ToolBar(toolbar => toolbar.Template(@<text>
                       <a class="k-button k-button-icontext k-grid-add" href="#"><span class="k-icon k-add"></span>New</a>
                       <a class="k-button k-button-icontext" id="cancelItem" 
href="javascript:void(0)"><span class="k-icon k-cancel"> </span>Cancel</a>

           </text>))
            .Editable(editable => editable.Mode(GridEditMode.InCell))
            .Filterable()
            .Sortable()
            .DataSource(dataSource => dataSource
            .Ajax()
            .Batch(true)
            .ServerOperation(false)
            .Model(model =>
                       {
                       model.Id(row => row.Id);
                       }
                       )
            .ServerOperation(false)
            .PageSize(25)
            )
            .Resizable(resize => resize.Columns(true))
            .Selectable(selectable => selectable.Mode(GridSelectionMode.Multiple))
            .Reorderable(reorder => reorder.Columns(true))
            .Pageable(p => p.PageSizes(new[] { 25, 50, 100 }))
 )



Below are the key configurations. We defining that our grid is multi selectable. Also we defined Cancel button in Grid toolbar


.Selectable(selectable => selectable.Mode(GridSelectionMode.Multiple))

<a class="k-button k-button-icontext" id="cancelItem" href="javascript:void(0)"><span class="k-icon k-cancel"></span>Cancel</a>

Now its time to define the Javascript, which will remove the grid item. Find the INLINE comments for the below code.


// adding click event for cancel button

$("#cancelItem").on("click", function (e) { 
           clearSelectedRows("UserGrid"); 
 });

clearSelectedRows = function (gridName) {

           // identifying grid

            var entityGrid = $("#" + gridName + "").data("kendoGrid");

            // finding all the selected rows
            var rows = entityGrid.select();
            rows.each(function (index, row) {

                        // reading each selected item
                         var selectedItem = entityGrid.dataItem(row);

                       // finally removing selected item from grid data source
                         entityGrid.dataSource.remove(selectedItem); 
              });
 }

Happy Kooding… Hope this helps….!

How to use Kendo Validator / Kendo Validation

For example, I have form which has Salary as input field, now I would like to perform custom validation on this field.

HTML


<div id="DataEntryDiv" style="margin-top:20px">
<div class="editor-label">Salary</div>
<div class="editor-field">
<input id="Salary" type="number" class="input" name="Salary" data-bind="value: Salary" />
</div>
</div>

JAVASCRIPT


<script type="text/javascript">
var myValidator = $("#DataEntryDiv").kendoValidator({

rules: {
SalaryRule: function (input) {
if (input.is("[name=Salary]")) {
return !(parseInt($("#Salary").val()) <= 0);
}
return true;
}
},
messages: {
SalaryRule: "Value must be greater than 0",
},
validateOnBlur: false
}).data("kendoValidator");

function onSave(e) {
if (!myValidator.validate()) {
e.preventDefault();
}
}
</script>

This works with Kendo Grid Pop as well. All you have to do is hook up the save event for kend Grid


@(Html.Kendo().Grid<MyModelClass>()
.Name("myKendoGrid")

.Events(e => e.Save("onSave"))

Happy Kooding… Hope this helps!

Tips/Tricks about KENDO

1) KENDO GRID: At anygiven time, if you want to access the edited or added data (before reload of grid/save)

var editableModel = $('#myGrid').data().kendoGrid.editable.options.model;

2) KENDO GRID: If you would like to update one of the property value manually for recent edited record in grid then


var editableModel = $('#myGrid').data().kendoGrid.editable.options.model;
editableModel.set("dobDate", '05/31/1983');

3) MONTH PICKER: Implementing month picker with Kendo. This would work with Grid Edit Pop also.

<input id="dobDate" type="date" class="input" name="dobDate" data-bind="value: dobDate" />
$(document).ready(function () {
 

$("#dobDate").kendoDatePicker({
start: "year",
depth: "year",
format: "MMMM yyyy",
parseFormats: ["MMMM yyyy"]
});


});

Month Picker cannot be achieved with Model binder as there is a known bug. The only available is the above

4) KENDO GRID: Format/Parse the date column (bound column)

columns.Bound(m =&amp;gt; m.DobDate).Width(50).Title("Dob Date").ClientTemplate("#= DobDate &amp;lt; 1/1/1900 ? '' : &nbsp; kendo.format('{0:MMMM yyyy}', DobDate) #")

5) KENDO DATE PICKER: Disable the control by editing it

<input id=”dobDate” type=”date” class=”input” name=”dobDate” onkeydown=”return false;”  data-bind=”value: dobDate” />

6) KENDO FILTER OPERATORS: Below are the few filter operators

  filter.push({ field: "IsNew", operator: "eq", value: 1 });

eqgtgteltteneq

7) READONLY:

 @(Html.Kendo().DatePicker().Value(DateTime.Now)
 .Name("myDate").Min(DateTime.Now)
 .HtmlAttributes(new { style = "width: 100%", @readonly="readonly" }))

or


$("#myDate").kendoDatePicker(); 

var myDate= $("#myDate").data("kendoDatePicker"); 

myDate.readonly(true);

8) NUMERIC TEXTBOX: Don’t allow decimal value and don’t allow negative value (define min value)

a) format allows you to ignore/avoid entering decimal value

b) min allows you to set the min value to zero


$("#Hours").kendoNumericTextBox({ decimals: 0, format: "#", min: 0 });

9) HIDE/SHOW KENDO DROPDOWNLIST: Below is the syntax to hide/show kendo dropdownlist
HIDE:

 $("#ddlCountries").closest(".k-widget").hide();

SHOW:

 $("#ddlCountries").closest(".k-widget").show();

10) Kendo Grid Filter Configuration : For a Kendo Grid, if you would like to customize the filter menu below is how you can do


@(Html.Kendo().Grid<UserModel>()
    .Name("MyGrid")
    .ColumnMenu()
    .Filterable(f => f.Operators(o => o.ForString(s => s
        .Clear()
        .Contains("Contains")
        .DoesNotContain("Does not contain")
        .EndsWith("Ends with")
    )))
// other configuration goes
)

If you would like to customize to a specific column then you would do same above filter configuration to a column rather than entire grid


@(Html.Kendo().Grid<UserModel>()
    .Name("MyGrid")
    .Columns(columns =>
          {
              columns.Bound(m => m.UserName)
              .Filterable(f => f.Operators(o =>
              o.ForString(s => s.Clear().Contains("Contains")
              .DoesNotContain("Does not contain")
              .EndsWith("Ends with")
    )))

})
)

11) Kendo Grid Clear Selected Row :


            var grid = $("#myGrid").data("kendoGrid");
            grid.clearSelection();

Happy Koooding…..  Hope this helps!….