Kendo Grid doesn't send all checked items - kendo-ui

I have a Kendo Grid that has checked box items. I want to check all items and send them to the controller, for export checked data to PDF. But, when I have checked all items, Kendo Grid sends only checked items from the first page of grid, and my report in PDF has only one page. How to get all checked items from Kendo Grid? My code is here:
<div style="text-align:right; font-size: 0.9em;height:28px;position: relative;">
<span style="float:left;text-align:left;">
Check All
Uncheck All
<a class="k-button k-button-icontext k-grid-Patient" id="hrefCheckedPatients" href="#" onclick="getChecked();">Export to PDF</a>
Download Generated PDF
<label id="checkedMsg" style="color:red;display:none;"></label>
</span>
(Html.Kendo().Grid<RunSummary>()
.Name("CheckedPatients")
.DataSource(datasource => datasource
.Ajax().PageSize(25)
.Sort(sort => sort.Add("UniqueId").Ascending())
.Read(read => read.Action("GetRunSummaries", "PatientReport")))
.Columns(columns =>
{
columns.Bound(c => c.UniqueId).Title(ELSORegistry.Resources.Views.Home.HomeStrings.UniqueId)
.ClientTemplate("<input type='checkbox' class='primaryBox' id='#= UniqueId #'>#= UniqueId #</input>");
columns.Bound(c => c.RunNo).Title(SharedStrings.Run);
columns.Bound(c => c.Birthdate).Title(SharedStrings.Birthdate).Format("{0:g}").Filterable(true);
columns.Bound(c => c.customAge).Title(SharedStrings.Age)
.Filterable(
filterable => filterable
.UI("AgeFilter")
.Extra(false)
.Operators(operators => operators
.ForString(str => str.Clear().IsEqualTo("Is equal to"))
)
);
columns.Bound(c => c.TimeOn).Title(PatientStrings.DateOn)
.Format("{0:g}")
.Filterable(true);
columns.Bound(c => c.TimeOff).Title(PatientStrings.DateOff)
.Format("{0:g}")
.Filterable(true);
columns.Bound(c => c.DischargedAlive).Title(PatientStrings.DischargedAlive).Filterable(true).ClientTemplate("#= DischargedAlive ? 'Yes' : 'No' #");
columns.Bound(c => c.ShowSubmitted).Title(PatientStrings.Submitted).Filterable(true).ClientTemplate("#= ShowSubmitted ? 'Yes' : 'No' #");
columns.Bound(c => c.SupportTypeEnum).Title(PatientStrings.SupportType).Filterable(true);//.ClientTemplate("#= SupportType ? 'Yes' : 'No' #");
}
)
.Pageable(p => p.PageSizes(new[] {10, 25, 50, 100}))
.Sortable()
.Filterable( )
.Events( e => e.FilterMenuInit("FilterMenuFuncWithAge") ) // apply x [closing box] on pop up filter box
)
function getChecked() {
$('#checkedMsg').text('');
var ids = new Array();
$('.primaryBox:checked').map(function (index) {
ids.push(this.id);
});
if (ids.length == 0) {
$('#checkedMsg').text('#ELSORegistry.Resources.Views.Patient.PatientStrings.NoPatientsSelected').show();
$('#hrefCheckedPatients').blur();
return;
} else {
$('#checkedMsg').text('').hide();
$('#hrefCheckedPatients').blur();
}
$.ajax({
type: "POST",
url: "/PatientReport/ExportToPDF",
dataType: "json",
traditional: true,
data: { uniqueIds: ids },
success: function (data) {
if (data.success) {
$('#lnkPdfDownload').show();
$('#lnkPdfDownload').attr('href', '/PatientReport/DownloadFile' + '?fName=' + data.fName);
} else {
$('#lnkPdfDownload').hide();
}
},
error: function (jqXHR, textStatus, errorThrown) {
$('#checkedMsg').text('#ELSORegistry.Resources.Views.Patient.PatientStrings.CheckedError').show();
$('#hrefCheckedPatients').blur();
}
});
}
</script>
Thank you in advance for any help.

We can't get directly all Ids from the kendo grid from all pages. So we have to manually get it from all the pages.
Please try with the below code snippet.
<script>
var ids = [];
function checkAll() {
var dataSource = $("#CheckedPatients").data("kendoGrid").dataSource;
var filters = dataSource.filter();
var totalRowCount = parseInt(dataSource.total().toString());
var totalPages = Math.ceil(totalRowCount / dataSource.pageSize());
var currentPageSize = $("#CheckedPatients").data("kendoGrid").dataSource.page();
PageTraverser(dataSource, 1, totalPages,filters, function () {
$("#CheckedPatients").data("kendoGrid").dataSource.page(currentPageSize);
alert("You have slected this Ids:- " + ids.join(','));
});
}
function PageTraverser(dataSource, targetPage, totalPages,filters, completionFunction) {
dataSource.query({
page: targetPage,
filter: filters
pageSize: 1,
}).then(function () {
var view = dataSource.view();
for (var viewItemId = 0; viewItemId < view.length; viewItemId++) {
var viewItem = view[viewItemId];
ids.push(viewItem.UniqueId); //Please change your field name here
}
targetPage++;
if (targetPage <= totalPages) {
PageTraverser(dataSource, targetPage, totalPages, filters, completionFunction);
} else {
completionFunction();
}
});
}
</script>
Let me know if any concern.

Related

Hide column from grid while exporting to excel

I want to hide/remove one column when the data exported to excel..But that should be visible in grid. I have tried several solutions but not able find out the exact problem.
Currently excel is generating but unable to hide the column... Can anybody please help regarding this ?? Thanks in advance.
Here is my grid code:
#(Html.Kendo().Grid<Database.Model.UserSummaryInfo>()
.Name("Grid")
.Columns(col =>
{
col.Bound(c => c.ApplicationUserId).Hidden();
col.Bound(c => c.MemberId).Title("Member ID");
col.Bound(c => c.Visit).Title("Visit");
col.Bound(c => c.CreatedDate).Title("Visit Start Date");
col.Bound(c => c.LogInCount).Title("LogIn Count");
col.Bound(c => c.SurveyStatus).Title(" Survey Status");
col.Bound(c =>
c.ApplicationUserId).HeaderTemplate(#<text>Action</text>).ClientTemplate("#
if(SurveyStatus == 'Did Not Attempt') { #" + "<a class='btn btn-primary
disabled' style='display: none;' href='" + Url.Action("TestDetails",
"Admin") + "?id=#= TestSummaryId #&Year=#=Year#'" + " >Details</a>" + "#
}else{#" + "<a class='btn btn-primary enabled' style='width:60px' href='"
+ Url.Action("TestDetails", "Admin") + "?id=#= ApplicationUserId
#&Year=#=Year #&testSummaryId=#=TestSummaryId#'" + ">Details</a>" + "#
}#")
.HeaderHtmlAttributes(new { style = "text-align: center;font-size:18px"
});
})
.ToolBar(toolbar => toolbar.Template(#<text>
<div class="pull-left index-header">Test Summary</div>
<button type="button" class="btn btn-primary rounded pull-
right margin-right-10" onclick="clearFiter()"><i class="fa fa-times-
circle-o margin-right-5"></i> Clear Filter</button>
<a style="padding-right:5px;" class="k-button-icontext k-grid-
excel btn btn-primary pull-right margin-right-10" href="#"><span
class="fa fa-file-excel-o"></span>Export to Excel</a>
</text>))
.Excel(excel => excel
.FileName(DateTime.Now.Date.ToShortDateString() + " " +
"GetUserSummary.xlsx")
.AllPages(false)
.ProxyURL(Url.Action("Excel_Export_Save", "Admin")))
.Pageable(paging => paging.PageSizes(new int[] { 100, 500, 1000
}).Refresh(true).ButtonCount(5).Info(true).Input(true))
.Sortable(sortable =>
{
sortable.SortMode(GridSortMode.SingleColumn);
})
.Groupable()
.Scrollable(s => s.Height("auto"))
.Filterable(filterable => filterable.Operators(operators =>
operators.ForNumber(nmbr => nmbr.Clear().IsEqualTo("Is equal
to").IsLessThan("Less than").IsGreaterThan("Greater
than").IsNotEqualTo("Not equal to")).ForString(str =>
str.Clear().Contains("Contains").IsEqualTo("Is equal
to").StartsWith("Starts with").IsNotEqualTo("Is not equal
to")).ForDate(date => date.Clear().IsGreaterThan("Is
after").IsLessThan("Is Before").IsGreaterThanOrEqualTo("Is after or
equal to").IsLessThanOrEqualTo("Is before or equal to"))))
.Resizable(resize => resize.Columns(true))
.Events(e => e.ExcelExport("Hidecolumn"))
.DataSource(datasource =>
datasource
.Ajax()
.Sort(sort => {
sort.Add(c => c.MemberId).Ascending();
sort.Add(c => c.Visit).Ascending();
})
.PageSize(10)
.Read(read => read.Action("GetUserSummaryList", "Admin"))
)
)
</div>
</div>
</div>
<!-- End Content -->
</form>
</div>
<script>
var exportFlag = false;
$("#Grid").data("kendoGrid").bind("excelExport", function (e) {
debugger;
if (!exportFlag) {
e.sender.hideColumn(2);
e.preventDefault();
exportFlag = true;
setTimeout(function () {
e.sender.saveAsExcel();
});
} else {
e.sender.showColumn(2);
exportFlag = false;
}
});
function Hidecolumn(e) {
e.sender.hideColumn(2);
}
</script>
What you would need to do is to bind to the export function and then hide the columns similar to how you have above:
var exportFlag = false;
$("#grid").data("kendoGrid").bind("excelExport", function (e) {
if (!exportFlag) {
e.sender.hideColumn(1);
e.preventDefault();
exportFlag = true;
setTimeout(function () {
e.sender.saveAsExcel();
});
} else {
e.sender.showColumn(1);
exportFlag = false;
}
});
The exportFlag is due to stopping a recursive loop, because the saveAsExcel method fires the excelExport event.
Added this function to the excelExport event. We are knockout / jQuery but the logic should work for you.
It simply goes through all the rows in the sheet and deletes cells based on our excelHidden property.
self.resultsExcelExport = function(e) {
var sheet = e.workbook.sheets[0];
for (var i = this.columns.length - 1; i >= 0; i--) {
if (this.columns[i].excelHidden) {
sheet.columns.splice(i, 1);
sheet.rows.forEach(function(row) {
row.cells.splice(i, 1);
})
}
}
}
In the grid columns object add a property "excelHidden: true" to signal which columns to hide.
{
field: "Id",
title: 'Download',
excelHidden: true,
},
UPDATE:
Well that worked until I tried grouping a column. So had to lookup via title to find the correct column number to remove. Now looks like this.
function(e) {
var hiddenColumnsByTitle = {};
var hiddenColumns = [];
var sheet = e.workbook.sheets[0];
this.columns.forEach(function(column) {
if (column.excelHidden) {
hiddenColumnsByTitle[column.title] = true;
}
})
for (var r = 0; r < sheet.rows.length; r++) {
var row = sheet.rows[r];
if (row.type === "header") {
row.cells.forEach(function(headerCell, index) {
var columnTitle = headerCell.value;
if (hiddenColumnsByTitle[columnTitle]) {
hiddenColumns.push(index);
}
})
break;
}
}
for (var i = hiddenColumns.length - 1; i >= 0; i--) {
var hiddenColumn = hiddenColumns[i];
sheet.columns.splice(hiddenColumn, 1);
sheet.rows.forEach(function(row) {
row.cells.splice(hiddenColumn, 1);
})
}
}

Laravel Dynamic Dependent Dropdown

I need to add a Laravel Dynamic Dependent Dropdown. Im confused..
In my database, i have both categories and their childrens.
Account_id =0 => Categorie
Account_id =1 => Sub Categorie of category or subcategory with id =1
Account_id =2 => Sub categorie of category or subcategory with id =2
This is my actual code :
Method:
public function index()
{
$categories = Account::where('account_id', '=', 0)->get();
$allCategories = Account::where('account_id', '=', 0)-
>pluck('account_name','id');
return view('Account.list',compact('categories', 'allCategories')); //
set the path of you templates file.
}
public function children(Request $request)
{
return Account::where('account_id', $request->account_id)->pluck('account_name', 'id');
}
View:
<div class="form-group">
{!! Form::label('account_id', 'Parent Category:')!!}
{!! Form::select('account_id', $allCategories, ['placeholder' =>
'Choose Category'])!!}
</div>
<div class="form-group">
{!! Form::label('children', 'Child category:')!!}
{!! Form::select('children', [], null, ['placeholder' => 'Choose child
category'])!!}
</div>
Route:
Route::get('/categories', [
'uses' => 'AccountController#index',
'as' => 'categories'
]);
Route::get('/categories/children', [
'uses' => 'AccountController#children',
'as' => 'categories.children'
]);
JS:
<script>
$('#account_id').change(function(e) {
var parent = e.target.value;
$.get('/categories/children?account_id=' + account_id, function(data) {
$('#children').empty();
$.each(data, function(key, value) {
var option = $("<option></option>")
.attr("value", key)
.text(value);
$('#children').append(option);
});
});
});
</script>
try this first create new route
Route::post('subchildren/youcontroller', [
'as' => 'children.categories',
'uses' => 'youUrlController\yourController#childrenCategory',
]);
next create route go to controller create new method
public function childrenCategory(Request $request)
{
try {
$subCategory= subCategory::where('category_id', $request->nameSelectCategoryinYourView)->get();
return response()->json(['subCategory' => $subCategory], 200);
} catch (Exception $e) {
return response()->json(['error' => 'Error'], 403);
}
}
next in your view
<div class="form-group m-b-40">
<select name="subCategory" class="form-control p-0" id='subCategory'></select>
</div>
next in your javascript
jQuery(document).ready(function($) {
$('#FirstSelect').change(function () {
$('#subCategory').empty();
var Category = $(this).val();
datos = {
tipo : Category
},
$.ajax({
url: '{{ route('children.categories') }}',
type: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: datos,
success: function (argument) {
arreglo = {id:"a", tipo:""};
argument.detalles.unshift(arreglo);
$.each(argument.subCategory, function(index, el) {
var opcion = '<option value="'+ el.id +'">'+ el.subCategoryName+'</option>';
$('#subCategory').append( opcion );
});
}
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
})
});
});

How to fire Ajax function with radiobutton click MVC

I have a View made up of 3 Partial Views:
Partial View #1 is listing RadioButtons. When I click a button I would like to send the resulting selection to the controller in order to update the Partial View #2 (which is a Telerik grid). Then the selection in PV #2 will update Partial View #3 (another Telerik grid).
I am currently doing a Window.location to send selected values to the Controller which causes the Controller and ViewModel to be reloaded and lose state. Other than losing the state, the flow works as I would like.
Is there a way to do this in Ajax to where I do not have to reload the Controller?
I will spare you the Partial Views #2 & #3 of the Telerik grids. If I can get the answer to how to get the radio button to call the Controller without a postback, I can apply the same to those Partial Views.
View:
#model MyProject.ViewModel.MaterialsListVM
#{
ViewBag.Title = "Materials List";
}
<div>
<div class="row">
<div class="col-sm-2">
#Html.Partial("MaterialTypeFilter")
</div>
<div class="col-lg-10">
#Html.Partial("MaterialsGrid")
</div>
</div>
<div class="row"> </div>
<div class="row">
<div class="col-sm-2"> </div>
<div class="col-lg-10">
#Html.Partial("ProjectMaterialsGrid")
</div>
</div>
</div>
Partial View #1:
#model MyProject.ViewModel.MaterialsListVM
<div class="container">
<h5> #Html.Label("Material Type: ", new { style = "font-weight:bold;" })</h5>
#if (Model != null)
{
for (int i = 0; i < Model.Material_Type.MaterialTypeList.Count; i++)
{
<span class="btn-group-sm">
#Html.RadioButton("MatType", new { Model.Material_Type.MaterialTypeList[i].Name }, Model.Material_Type.MaterialTypeList[i].Selected, new { #onclick = "CallChangefunc(this.value)" })
#Html.Label(Model.Material_Type.MaterialTypeList[i].Name)
</span><br />
}
}
</div>
<script>
function CallChangefunc(value) {
var selected = value.replace("{ Name = ", "");
selected = selected.replace("}", "");
window.location = '#Url.Action("Index", "MaterialsList")' + '?selectedMatType=' + selected;
//alert("val is:" + selected);
}
Update
I changed the JavaScript to this Ajax call and that called my Controller HttpPost Index() function:
$(document).ready(function () {
$(':radio[name="MatType"]').change(function (e) {
$.ajax({
type: 'POST',
url: '/MaterialsList/Index',
data: { selectedMatType: $(':radio[name="MatType"]:checked').val()},
dataType: "json",
success: function (data) {
alert('did it');
}
});
});
})
Unfortunately the Controller is still being reloaded and I'm losing the state of the data selected into the Partial View #3 Telerik grid...
...any help would be much appreciated...
Update #2
This solution sucks but I don't know what else to do...
The goal is to retain the state of the datasource for a Telerik grid in Partial View #3. The datasource is a ViewModel with a List of class objects.
Added Partial View #2 code and ActionResult from Controller. There is no HttpPost Index function. Every radio button change fires the ActionResult Index. Every select event in Telerik grid fires ActionResult Index.
Pertinent Controller code:
public ActionResult Index(string selectedMatType, string selectedMaterials, string projectMaterialsList)
{
if (projectMaterialsList != null)
{
materialsListVM.ProjectMaterialsList = JsonConvert.DeserializeObject<List<ProjectMaterialsListVM.ProjectMaterial>>(projectMaterialsList);
}
if (selectedMatType != null)
{
materialsListVM.SelectMaterialType(selectedMatType);
materialsListVM.GetMaterials();
}
if (selectedMaterials != null)
{
string[] materialIds = selectedMaterials.Split(',');
foreach (string id in materialIds)
{
MoveToProjectMaterialsList(id, selectedMatType);
}
}
ViewBag.ProjectMaterialsList = materialsListVM.ProjectMaterialsList;
ViewBag.SelectedMatType = selectedMatType;
return View(materialsListVM);
}
Partial View #2 code:
#model MyProject.ViewModel.MaterialsListVM
<div>
#if (ViewBag.SelectedMatType == "Cap Weld")
{
#(Html.Kendo().Grid(Model.CapWeld_Materials)
.Name("grid")
.Columns(columns =>
{
columns.Select().Width(40);
columns.Bound(c => c.MaterialId).Hidden();
columns.Bound(c => c.MaterialTypeName);
columns.Bound(c => c.PcsPartNum);
columns.Bound(c => c.ClientPartNum);
columns.Bound(c => c.Type).Filterable(ftb => ftb.Multi(true));
columns.Bound(c => c.OuterDiameter).Filterable(ftb => ftb.Multi(true));
columns.Bound(c => c.WallThickness).Filterable(ftb => ftb.Multi(true));
columns.Bound(c => c.Specification).Filterable(ftb => ftb.Multi(true));
columns.Bound(c => c.Grade).Filterable(ftb => ftb.Multi(true));
})
.Events(ev => ev.Change("onChange"))
.Pageable()
.Sortable()
.Scrollable()
.TableHtmlAttributes(new { width = "100%" })
//.HtmlAttributes(new { style="height:500px"})
.PersistSelection(true)
.Filterable()
.DataSource(datasource => datasource
.Ajax()
.ServerOperation(false)
.Model(m => m.Id(d => d.MaterialId))
)
);
}
</div>
#{
var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
var val = jss.Serialize(ViewBag.ProjectMaterialsList);
}
<script>
function onChange(arg) {
var selectedMatType = '#(ViewBag.SelectedMatType)';
var projectMaterialsList = '#Html.Raw(val)';
//var obj = $.parseJSON(val);
var grid = $('#grid').data('kendoGrid');
var selectedMaterials = grid.selectedKeyNames().join(", ");
// alert(selectedMaterials);
#*$.ajax({
type: "POST",
data: { selectedMatType: selectedMatType, selectedMaterials: selectedMaterials, projectMaterialsList: projectMaterialsList },
dataType: "json",
url: #Url.Action("Index", "MaterialsList")
});*#
window.location = '#Url.Action("Index", "MaterialsList")' + '?selectedMatType=' + selectedMatType + '&selectedMaterials=' + selectedMaterials
+ '&projectMaterialsList=' + projectMaterialsList;
}
</script>

How to create page using Kendo Gird and Tabstrip

I want to select a row of grid and show detail row at tabstrip. The same image should attach.
Can anyone help me? I am using asp.net mvc 4 + Kendo Ui controls.
Image is here.
File CandidateController.cs
public ActionResult Index()
{
return View();
}
public ActionResult Can_Read([DataSourceRequest]DataSourceRequest request)
{
return Json(GetAllCan().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
public ActionResult Can_ReadId([DataSourceRequest]DataSourceRequest request, Guid id)
{
return Json(GetCanById(id).ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
In partial view: Candidate Info
#model RecruitmentOnlineMVC.Models.CandidateViewModel
<div class="candidate-detail" style="width: 827px!important">
<table>
<tr>
<th>Candidate Name</th>
<td>#(Html.TextBoxFor(model => model.CandidateName, new { #class = "k-input k-textbox" }))</td>
<th>ID</th>
<td>#Html.TextBoxFor(model => model.ID, new { #class = "k-input k-textbox" })</td>
</tr>
<tr>
<th>Email</th>
<td>#Html.TextBoxFor(model => model.Email, new { #class = "k-input k-textbox" })</td>
<th>Phone</th>
<td>#Html.TextBoxFor(model => model.Phone, new { #class = "k-input k-textbox" })</td>
</tr>
</table>
</div>
In View Index
#model RecruitmentOnlineMVC.Models.CandidateViewModel
#(Html.Kendo().Splitter()
.Name("splitter")
.Panes(panes =>
{
panes.Add()
.Content(#<div>
#(Html.Kendo().Grid<RecruitmentOnlineMVC.Models.CandidateViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.CandidateName);
columns.Bound(c => c.ID);
})
.Selectable(selectable => selectable
.Mode(GridSelectionMode.Single))
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Read(read => read.Action("Can_Read", "Candidate"))
)
.Pageable(pageable => pageable.ButtonCount(3))
.Filterable()
.Sortable()
.ColumnMenu()
.Events(e => e.Change("onSelected"))
)
</div>)
.Scrollable(true)
.Collapsible(true)
.Size("370px");
panes.Add()
.Content(#<div>
#(Html.Kendo().TabStrip()
.Name("tabstrip")
.Items(tabstrip =>
{
tabstrip.Add().Text("Candidate Detail")
.Selected(true)
.LoadContentFrom("/Candidate/CandidateInfo");
tabstrip.Add().Text("Work History")
.LoadContentFrom("/Candidate/WorkHistory");
})
)
</div>);
}))
Script
<script>
function onSelected() {
var can = this.select();
var propId = this.dataItem(can).ID;
\\In here, I want call action at Controller with propId and return detail on Tabstrip
Can anyone help me?
Thank so much !
I want to handled according to process like this :
Please guide me. Thank so much!
You need to make a seprate function in you controller with Json http post
and calls ajax request from the OnSelected() function..
following is the example
//Get Company List
[HttpPost]
public JsonResult GetCandidateDetails(string propId)
{
var Model= repository.GetCnadidatedetails(propId);
return Json(Model), JsonRequestBehavior.AllowGet);
}
<script>
function onSelected() {
var can = this.select();
var propId = this.dataItem(can).ID;
var dataItem = this.dataItem(e.item.index());
$.ajax({
url: '#Url.Action("GetCnadidatedetails", "Controller")',
//note: only string type is allowed as paramater to send to controller
data: { propId : this.propId },
dataType: "json",
type: "POST",
statusCode: {
404: function () {
showMessage("page not found.");
}
},
error: function () {
alert("error");
},
success: function (result) {
//add your result to tabstripe
$("#tabstrip").add(result.Id+result.Name);
}
});

Highlight selected TELERIK MVC GRID row text in BOLD

I have a Telerik MVC Grid where I have a column as " select " , " edit" forwhich I have used Format Property to show Links to my ActionMethods . Now I want to show the selected Row text in Bold when someone clicks on " Select" / " Edit " link ?
How to achieve this using JQuery / Javascript ? Tried using RowAction but couldnt sort out this as I am using Format Property and Ajax.ActionLink for Select and Edit ActionLinks.
<% Html.Telerik().Grid(Model.GetLegends)
.Name("PaymentScheduleLegendGrid")
.ToolBar(toolBar => toolBar.Template(() =>
{
%>
<label style="height:10px; float:left;padding-right:230px;" >Legend</label>
<%= Ajax.ActionLink("Add", "AddLegend", "PaymentSchedule", new AjaxOptions { OnSuccess = "updateTarget", UpdateTargetId = "addlegend", HttpMethod = "Get" }, new { Style="text-decoration:underline;" })%>
<%
})).HtmlAttributes("style='background:none grey'")
.DataKeys(dataKeys => dataKeys.Add(m => m.LegendId))
.Columns(columns =>
{
// columns.Bound(m => m.Legend_color).ClientTemplate("<div><div style='float:right;text-align:left;width:80%'><#= legend_name #></div>" + "<div style='padding:3px;background-color:<#= legend_color #>;width:20px;height:15px'></div></div>").Title("Legend");
columns.Bound(m => m.LegendColor).Format(Html.ColorBlock("{0}").ToHtmlString()).Encoded(false).Title("");
columns.Bound(m => m.LegendId).Hidden(true).HeaderHtmlAttributes(new { #class = "newBack" }); ;
columns.Bound(m => m.LegendName).Title("");
columns.Bound(m => m.LegendId).Title("").Format(Ajax.ActionLink("Select", "Select", "PaymentSchedule", new { Id = "{0}" }, new AjaxOptions { OnSuccess = "updateTarget", UpdateTargetId = "AddPaymentSchedule", HttpMethod = "Get" }, new { Style = "text-decoration:underline;" }).ToHtmlString().Replace("{", "{{").Replace("}", "}}")).Encoded(false).Width(60);
columns.Bound(m => m.LegendId).Title("").Format(Ajax.ActionLink("Edit", "EditLegend", "PaymentSchedule", new { Id = "{0}" }, new AjaxOptions { OnSuccess = "updateTarget", UpdateTargetId = "addlegend", HttpMethod = "Get" }, new { Style = "text-decoration:underline;" }).ToHtmlString().Replace("{", "{{").Replace("}", "}}")).Encoded(false).Width(60);
})
// .RowAction(row => row.Selected = row.HtmlAttributes.Add("style", "background:#321211;"))
.Sortable()
.Selectable().HtmlAttributes("style=font:bold")
.DataBinding(databinding => databinding
.Ajax().Select("AjaxIndex", "Legend"))
.Pageable(pager => pager.PageSize(5))
.Render();
%>
This is my code and When user clicks on Select / Edit ActionLink ... Selected LegendName should be highlighted in bold . When I use Selectable property I am getting the selected row as highlighted ( new Background color for selected row which doesnt satisfy my requirement). Besides that I have one more requirement , I want to change the background color of my toolbar to GREY . Can you please help me
In order to apply certain style for certain table row you need to use CSS. For server side binding you can use the HtmlAttributes from RowAction. However I don't know (as you haven't described) how to determine if a row is selected inside the RowAction method. If you want a more concrete answer I suggest you attach a running project which shows the entire scenario in the forum thread which you opened in the Telerik forums.
If you want to do that client-side you can use jQuery:
<%: Html.Telerik().Grid().ClientEvents(e => e.OnLoad("onLoad")) %>
<script>
function onLoad() {
$(this).delegate("tr a", "click", function(e){
$(this).closest("tr").addClass("t-state-selected") // add the css class
.siblings()
.removeClass("t-state-selected") // remove css class from other rows
});
}
</script>
So far I have done this .
<style type="text/css">
#PaymentScheduleLegendGrid table thead
{
}
.newBack
{
background:none grey;
}
.newBoldtext
{
font-weight:bold;
color:red;
}
</style>
<script type="text/javascript">
function onLoad() {
$(this).delegate("tr a", "click", function (e) {
$(this).closest("tr").addClass("newBoldtext"); // or any other CSS class
});
}
</script>
<div>
<% Html.Telerik().Grid(Model.GetLegends)
.Name("PaymentScheduleLegendGrid")
.ToolBar(toolBar => toolBar.Template(() =>
{
%>
<label style="height:10px; float:left;padding-right:230px;" >Legend</label>
<%= Ajax.ActionLink("Add", "AddLegend", "PaymentSchedule", new AjaxOptions { OnSuccess = "updateTarget", UpdateTargetId = "addlegend", HttpMethod = "Get" }, new { Style="text-decoration:underline;" })%>
<%
})).HtmlAttributes("style='background:none grey'")
.DataKeys(dataKeys => dataKeys.Add(m => m.LegendId))
.ClientEvents(e => e.OnLoad("onLoad"))
.Columns(columns =>
{
columns.Bound(m => m.LegendColor).Format(Html.ColorBlock("{0}").ToHtmlString()).Encoded(false).Title("");
columns.Bound(m => m.LegendId).Hidden(true).HeaderHtmlAttributes(new { #class = "newBack" }); ;
columns.Bound(m => m.LegendName).Title("test");
columns.Bound(m => m.LegendId).Title("")
.Format(Ajax.ActionLink("Select", "Select", "PaymentSchedule",
new { Id = "{0}"}
, new AjaxOptions { OnSuccess = "updateTarget", UpdateTargetId = "AddPaymentSchedule", HttpMethod = "Get" }
, new { name = "SelectRow", Style = "text-decoration:underline;" }
).ToHtmlString().Replace("{", "{{").Replace("}", "}}")).Encoded(false).Width(60);
columns.Bound(m => m.LegendId).Title("").Format(Ajax.ActionLink("Edit", "EditLegend", "PaymentSchedule", new { Id = "{0}" }, new AjaxOptions { OnSuccess = "updateTarget", UpdateTargetId = "addlegend", HttpMethod = "Get" }, new { Style = "text-decoration:underline;" }).ToHtmlString().Replace("{", "{{").Replace("}", "}}")).Encoded(false).Width(60);
})
.Sortable()
.Selectable().HtmlAttributes("style=font:bold")
.DataBinding(databinding => databinding
.Ajax().Select("AjaxIndex", "Legend"))
.Pageable(pager => pager.PageSize(10))
.Render();
%>

Resources