Kendo Grid changing a column Text - MVC 5 , Razor - asp.net-mvc

I want to remove/hide the hyperlink of a cell/row based on a condition, I'm using Kendo UI for MVC with Razor.
The first column is bound with "View" hyperlink. Which I need to be controlled (remove/hide) based on the values of another column in the same grid i.e. the 2nd column "LastName".
i.e. when the item bound to the grid need to do the below logic.
If current [LastName] == previous [LastName] then hide View hyperlink, so i will have only one view link for the users with same last name.
Appreciate any help or suggestions. Below is my code to ender the grid.
#model IEnumerable<EDM2_UI.Models.ReportsViewModel>
#(Html.Kendo().Grid(Model)
.Name("advancedGrid")
.Columns(columns =>
{
columns.Bound("ReportID").ClientTemplate("View").Title("").Width(50).Filterable(false);
columns.Bound(p => p.LastName).Title("Last Name").Width(130);
columns.Bound(p => p.TestName).Title("Test Name").Width(130).Filterable(false);
columns.Bound(p => p.TestDate).Width(130);
})
.Pageable()
.Sortable()
.Scrollable(scr => scr.Height(500))
.Resizable(resize => resize.Columns(true))
.Filterable()
.Groupable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(100)
.ServerOperation(false)
)
)

You should be able to put a conditional statement inside the ClientTemplate. First you need to define the URL in the view model and leave it blank where it is not needed. Then something like this should work in your views:
.ClientTemplate("# if (ReportIDLink != '') { # <a href='#= ReportIDLink # '>View</a> # } else { # <div>#= ReportID #</div> # } #")

Related

Telerik Kendo Grid Doesn't Display Value Properly

i'm new to kendo UI and currently learning about custom editor.
My Problem is i managed to get my editor template working in edit mode and populate the data just fine, but somehow it won't save the value to the display grid
I Retreive all my data from API.
UPDATE:
i've managed to properly save the value from the custom editor template to the controller and it works just fine, but using clientTemplate won't display the correct value from what i select in the dropdown, and only show a string
DropDown Only Display A String
my setup code is like this
#( Html.Kendo().Grid<SalesOrderDetailVM>()
.Name("list-detail")
.Columns(columns =>
{
columns.Bound(c => c.Product).ClientTemplate("\\#=Product.ProductId\\#").Title("Products");
columns.Bound(c => c.Quantity);
columns.Bound(c => c.UnitPrice);
})
.Editable(GridEditMode.InCell)
.ToolBar(tool =>
{
tool.Create();
tool.Save();
}
)
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(false)
.Batch(true)
.Model(model =>
{
model.Id(p => p.ProductId);
model.Field(p => p.Product);
})
.Create(act => act.Action("DetailCell_Create","SalesOrder"))
)
)
DDLProduct.cshtml:
#model AAF.WEB.MVC.ViewModels.ProductVM
#(
Html.Kendo().DropDownListFor(m => m)
.DataValueField("ProductId")
.DataTextField("ProductName")
.OptionLabel("Select Product")
.BindTo((System.Collections.IEnumerable)ViewData["products"])
)
Edit Mode
DisplayMode / Out of Product Edit Mode
Use template method to acheive dropdown with kendo grid.
GridForeignKey.cshtml - it should placed in shared folder or EditorTemplates
#model object
#(
Html.Kendo().DropDownListFor(m => m)
.BindTo((SelectList)ViewData[ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Data"])
)
In your kendo grid please change like below
#( Html.Kendo().Grid<AAF.WEB.MVC.ViewModels.SalesOrderDetailVM>()
.Name("list-detail")
.Columns(columns =>
{
columns.Bound(c => c.Id)
columns.ForeignKey(c => c.ProductId, (System.Collections.IEnumerable)ViewData["Products"], "ProductId", "ProductName").Title("Products");
columns.Bound(c => c.Quantity);
columns.Bound(c => c.UnitPrice);
})
.Editable(GridEditMode.InCell)
.ToolBar(tool =>
{
tool.Create();
tool.Save();
}
)
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(false)
)
)
You can set the products data to view data. using this method you can save the product id.
Thanks
Okay after i frustrated for many hours, finally found the solution
the solution is to add a defaultvalue to the passed model in the grid
.Model(model =>
{
model.Id(p => p.ProductId);
model.Field(p => p.Product).DefaultValue(
ViewData["defaultProduct"] as ProductVM
);
})
and pass the data from the controller
// Function that get data from API
ViewData["products"] = products;
ViewData["defaultProduct"] = products.First();

Dropdown list in ASP MVC Kendo grid will not open

I am trying to replicate exactly what is on this Kendo demo page with the Categories column. Simply a drop down list inside the grid. I copied all their source code exactly, but when I click the column with a drop down, the grid simply flashes. I can edit the FullName value fine. I tried to get an animation of the effect with a screen recorder, but for some reason it is not showing everything I see. In this image I am clicking the "Rol" drop down column multiple times.
What the gif does not show is that when I click the column, it briefly changes to a drop down control for a split second. I was able to capture this by adding a "debugger" line to the onDataBound event for the dropdown and taking a screenshot:
What is going on? Why doesn't it just pop open?
Here is some of the relevant code:
The EditorTemplates/RolList.cshtml file. Note that NONE of these events fire except the onDataBound event. That is probably a clue.
#model MyCompany.Web.CaseLink.Mvc.Admin.Models.RolDropDown
#(Html.Kendo().DropDownListFor(m => m)
.BindTo((System.Collections.IEnumerable)ViewData["roles"])
.DataValueField("RolId")
.DataTextField("RolDescription")
.Events(events => events
.Select("onSelect")
.Change("ddlChange")
.Open("onOpen")
.DataBound("onDatabound")
)
)
<script type="text/javascript">
function onSelect(e) {
console.log("ddl select" + e);
}
function ddlChange(e) {
console.log("ddl change" + e);
}
function onOpen(e) {
console.log("ddl open" + e);
}
function onDatabound(e) {
debugger;
console.log("ddl databound" + e);
}
</script>
Here is the partial view containing the MVC Grid itself. Note that the gridChange event was added just for debugging, and it does not fire when clicking in the drop down column.
#(Html.Kendo().Grid<CaseMemberGridRow>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.FullName)
.Title("Name")
;
columns.Bound(p => p.Rol).ClientTemplate("#=Rol.RolDescription#").Width(180);
columns.Bound(c => c.Email)
.Title("Email")
;
columns.Bound(c => c.Telephone)
.Title("Phone")
;
columns.Command(command => command.Destroy()).Width(150);
})
.ToolBar(toolBar =>
{
toolBar.Create();
toolBar.Save();
})
.HtmlAttributes(new { style = "height: 550px;" })
.Scrollable()
.Sortable()
.Editable(editable => editable.Mode(GridEditMode.InCell))
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(false)
.Events(events => events.Error("error_handler").Change("gridChange"))
.Model(m =>
{
m.Field(p => p.FullName).Editable(true);
m.Field(p => p.Rol).Editable(true);
m.Field(p => p.Rol).DefaultValue(
ViewData["defaultRol"] as MyCompany.Web.CaseLink.Mvc.Admin.Models.RolDropDown);
})
.Create(create => create.Action("AddCaseMemberNoCustomerRecord_Create", "AddMember"))
.Update(update => update.Action("AddCaseMemberNoCustomerRecord_Update", "AddMember"))
)
)
Controller is nothing special, as I said, I am doing exactly when Telerik did in their demo. A sample:
var roles = _rolService.GetAllRolesDTO()
.OrderBy(o => o.Description)
.Select(r => new RolDropDown
{
RolDescription = r.Description,
RolId = r.RolId
});
ViewData["roles"] = roles;
ViewData["defaultRol"] = roles.First();
If there is something to look for in the debugger on the "onDataBound" event, let me know. As you can see here, the datasource is definitely populated.
EDIT: I am aware that you can attempt to do the same thing using the ForeignKey type of column. When I try that, I can get a drop down to work once. After selecting a value, the column starts acting like before where you cannot change the value.
columns.ForeignKey(p => p.RolId, (System.Collections.IEnumerable)ViewData["roles"], "RolId", "Description")
.Title("Role")
.Width(150);

How can i delete multi selected records using checkbox in Kendo Grid?

I want to allow the user to select one or more rows using checkbox in kendo grid and to delete the selected rows, my project is asp.net MVC
How can i add the checkbox in order to allow the user to select it?
How to delete all selected rows? i.e rows with selected checkbox
anyone can suggest me how can i do this?
#(Html.Kendo().Grid<TelerikMvcAppCombo.Models.ImageModel>()
.Name("grdImageModel")
.Columns(columns =>
{
columns.Bound(c => c.IMAGESIZE_NAME).Width(140);
columns.Bound(c => c.IMAGESIZE_DESC).Width(140);
columns.Bound(c => c.created_by);
columns.Bound(c => c.created_date);
columns.Bound(c => c.modified_by);
columns.Bound(c => c.modified_date);
})
.HtmlAttributes(new { style = "height: 580px;" })
.Scrollable()
.Groupable()
.Sortable()
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(10)
)
.DataSource(datasource => datasource
.Ajax()
.Read(read => read
.Action("GetData", "Image")
))
)
In kendo grid add this column
columns.Template(x => { }).ClientTemplate("<input type='checkbox' id='chkSelect_#= yourid#' userId='#= yourid#' />").Width(20);
and lets say you have a button to delete records and when we click that button you can loop the data source and delete records. See the JavaScript example. You have to use jquery to do that
var grid, dataSource, data = null;
grid = $("#grdImageModel").data("kendoGrid"), dataSource = grid.dataSource, data = dataSource.data();
$.each(data, function (i, tmpObject) {
$('tr[data-uid="' + tmpObject.uid + '"] td input[id^="chkSelect_"]:checked').each(function (k, input) {
// here you are access the checked row object
});
});

MVC Kendo Grid Hyperlink column

I want this first column 'Name' should be a 'hyperlink' template .But value should be binded from model for that hyper link each link have different name that comes from property of the model. How to do this? I tried in the following way its working good .!!
But I am getting all rows first column's hyperlink text as "Show Product Details". I want to get model values. I don't want it to be same for all columns
#(Html.Kendo().Grid<Cutomers.Model.CustomerDataModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.Name).ClientTemplate("Show Product Details");
columns.Bound(c => c.CreatedDate).Width(70);
columns.Bound(c => c.CreatedBy).Width(70);
})
.HtmlAttributes(new { style = "height: 350px;" })
.Scrollable()
.Groupable()
.Sortable()
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(1))
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Customers_Read", "Home"))
)
)
I don't think you can use Razor syntax in there, try..
.ClientTemplate("#AnotherModelPropertyHere#")

Changing row color in Kendo MVC grid, using RowAction

I'm hoping to use RowAction with a lambda to set the background color of a few rows of data in a Grid.
<%: Html.Kendo().Grid<HomeController.SuccessfulBuildsByDevice>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.A);
columns.Bound(p => p.B);
})
.Scrollable()
.Sortable()
.Filterable()
.RowAction(row =>
{
if(row.DataItem.A > row.DataItem.B)
row.HtmlAttributes["style"] = "background:red";
})
.HtmlAttributes(new { style = "height:500" })
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("_GetData", "Home"))
.ServerOperation(false)
)
%>
However, when I use the above the RowAction() doesnt seem to be called. I tried setting a breakpoint, etc. Am I missing something in the intended use of RowAction(), does anyone see an obvious problem?
the problem is .Ajax() and .RowAction() are mutually exclusive
http://www.kendoui.com/forums/kendo-ui-web/grid/ajax-binding-and-rowaction-conflict-.aspx
Just because I came accorss this issue today and to save time here the short answer that worked for me based on the explanation from stuck
add this to the grid
.Events(e => e.DataBound("onDataBound"))
add this javascript above the grid
function onDataBound() {
// get the grid
var grid = this;
// iterate through each row
grid.tbody.find('>tr').each(function () {
// get the row item
var dataItem = grid.dataItem(this);
// check for the condition
if (dataItem.IsArchived) {
// add the formatting if condition is met
$(this).addClass('bgRed');
}
})
}

Resources