How to hide one column based on condition in kendo grid - kendo-grid

Below is my kendo grid in this grid I need to hide Case Number column conditionally that means if(admin == true) I need to show this column or else I need to hide this column how can I do this
#(Html.Kendo().Grid(Model.GiIncidentReportList)
.Name("IRGrid").Columns(columns => {
columns.Bound(r => r.IncidentReport).Title("Case Number");
columns.Bound(r => r.IncidentCreatedByName).Title("Created By");
columns.Bound(r => r.IncidentCreatedDateTime).Title("Created Date");
columns.Bound(r => r.IncidentUpdatedByName).Title("Updated By");
columns.Bound(r => r.IncidentUpdatedDateTime).Title("Updated Date");
columns.Template(p =>
#Html.ActionLink("Delete","DeleteIncidentReport","IncidentReport",
new { incidentReportId = p.IncidentReport.IR_IncidentID, dlLogId = p.IncidentReport.DL_LogID, incidentType = p.IncidentReport.IT_IncidentType },
new { #class = "k-button k-button-icontext", onclick = "return confirm('Are you sure you wish to delete this report?')" }).ToHtmlString()
);
})
)
What I tried
if(admin == true){
var grdView = $('#IRGrid').data('kendoGrid');
grdView.hideColumn("IncidentReport"); //By Using Columns Name.
}
It is working but I want to handle the show and hide at columns.bound only instead of using if condition.

Have your admin property in your model and use .Hidden(#Model.admin) property to show hide the column
#(Html.Kendo().Grid(Model.GiIncidentReportList)
.Name("IRGrid").Columns(columns => {
columns.Bound(r => r.IncidentReport).Title("Case Number").Hidden(#Model.admin);
columns.Bound(r => r.IncidentCreatedByName).Title("Created By");
columns.Bound(r => r.IncidentCreatedDateTime).Title("Created Date");
columns.Bound(r => r.IncidentUpdatedByName).Title("Updated By");
columns.Bound(r => r.IncidentUpdatedDateTime).Title("Updated Date");
columns.Template(p =>
#Html.ActionLink("Delete","DeleteIncidentReport","IncidentReport",
new { incidentReportId = p.IncidentReport.IR_IncidentID, dlLogId = p.IncidentReport.DL_LogID, incidentType = p.IncidentReport.IT_IncidentType },
new { #class = "k-button k-button-icontext", onclick = "return confirm('Are you sure you wish to delete this report?')" }).ToHtmlString()
);
})
)

You can pass the Value through #Viewbag and give the condition like this
#(Html.Kendo().Grid(Model.GiIncidentReportList)
.Name("IRGrid").Columns(columns => {
if (#ViewBag.admin == "True")
{
columns.Bound(r => r.IncidentReport).Title("Case Number");
}
columns.Bound(r => r.IncidentCreatedByName).Title("Created By");
columns.Bound(r => r.IncidentCreatedDateTime).Title("Created Date");
columns.Bound(r => r.IncidentUpdatedByName).Title("Updated By");
columns.Bound(r => r.IncidentUpdatedDateTime).Title("Updated Date");
columns.Template(p =>
#Html.ActionLink("Delete","DeleteIncidentReport","IncidentReport",
new { incidentReportId = p.IncidentReport.IR_IncidentID, dlLogId = p.IncidentReport.DL_LogID, incidentType = p.IncidentReport.IT_IncidentType },
new { #class = "k-button k-button-icontext", onclick = "return confirm('Are you sure you wish to delete this report?')" }).ToHtmlString()
);
})
)

Related

DEVEXTREME Save all selected data in grid inside edit form to database

multiple select item in Edit form with grid
How to save the data included the selected item at grid using DEVEXTREME.
The condition now is i can show the grid but now i struggle on get all the data inside the grid to save it and bring it to database, including need to show it again when the user want to edit the data
Template:
#using (Html.DevExtreme().NamedTemplate("EmbeddedDataGridMultiple"))
{
#(Html.DevExtreme().DataGrid()
.ID("PrincipalGrid")
.DataSource(d => d.WebApi().Controller("MasterPrincipal").LoadAction("GetPrincipalData").Key("PrincipalId"))
.Columns(columns => {
columns.Add().DataField("Principal");
columns.Add().DataField("Description");
})
.HoverStateEnabled(true)
.Paging(p => p.PageSize(10))
.FilterRow(f => f.Visible(true))
.Scrolling(s => s.Mode(GridScrollingMode.Virtual))
.Height(345)
.Selection(s => s.Mode(SelectionMode.Multiple))
.SelectedRowKeys(new JS(#"component.option(""value"")"))
.OnSelectionChanged(#<text>
function(selectedItems) {
var keys = selectedItems.selectedRowKeys;
component.option("value", keys);
}
</text>)
)
}
Form
#(Html.DevExtreme().DataGrid<MasterGroupQuotaValidateModel>
()
.ID("gridData")
.ShowBorders(true)
.DataSource(d => d.Mvc().Controller("MasterGroupQuota")
.LoadAction("GetGroupQuota")
.Key("IdGroup")
.UpdateAction("UpdateMasterGroupQuota")
.DeleteAction("DeleteMasterGroupQuota")
.InsertAction("InsertMasterGroupQuota")
)
.RemoteOperations(true)
.Columns(columns =>
{
columns.AddFor(m => m.RowNumber).Caption("No").Width(70);
columns.AddFor(m => m.GroupQuotaId).Visible(false);
columns.AddFor(m => m.SitePlan)
.Lookup(lookup => lookup
.DataSource(d => d.WebApi().Controller("MasterSite").LoadAction("GetSitePlan").Key("SiteId"))
.DisplayExpr("SitePlan")
.ValueExpr("SiteId")
).ValidationRules(rules =>
{
rules.AddAsync().ValidationCallback("CheckGroupQuota").Message("This Site is already registered with the follwoing GroupQuota and Principal");
}); ;
columns.AddFor(m => m.Description).Caption("Group Quota").ValidationRules(rules =>
{
rules.AddAsync().ValidationCallback("CheckGroupQuota").Message("This Group Quota is already registered with the follwoing Site Plan and Principal");
});
columns.AddFor(m => m.Principal)
.Lookup(lookup => lookup
.DataSource(d => d.WebApi().Controller("MasterPrincipal").LoadAction("GetPrincipalData").Key("PrincipalId"))
.DisplayExpr("Principal")
.ValueExpr("PrincipalId")
).ValidationRules(rules =>
{
rules.AddAsync().ValidationCallback("CheckGroupQuota").Message("This Principal is already registered with the follwoing GroupQuota and Site Plan");
});
})
.Paging(paging => paging.PageSize(5))
.Pager(pager =>
{
pager.Visible(true);
pager.ShowPageSizeSelector(true);
pager.AllowedPageSizes(new JS("[5, 10, 'all']"));
pager.ShowInfo(true);
pager.ShowNavigationButtons(true);
})
.Sorting(sorting=> sorting.Mode(GridSortingMode.Single))
.FilterRow(f => f.Visible(true))
.HeaderFilter(f => f.Visible(true))
.AllowColumnReordering(true)
.ShowBorders(true)
.Grouping(grouping => grouping.AutoExpandAll(true))
.SearchPanel(searchPanel => searchPanel.Visible(true))
.GroupPanel(groupPanel => groupPanel.Visible(true))
.HoverStateEnabled(true)
.ShowRowLines(true)
.RowAlternationEnabled(true)
.Scrolling(scrolling => scrolling.RowRenderingMode(GridRowRenderingMode.Virtual))
.Selection(s => s.Mode(SelectionMode.Single))
.OnSelectionChanged("gridSelectionChanged")
.OnExporting("exporting")
.OnRowUpdating("RowUpdating")
.OnEditorPreparing("onEditorPreparing")
.OnSaved("setItemTreeToTextSaving")
.OnEditingStart(#<text>
function(e) {
GetKeyId(e.key)
}
</text>)
.Editing(e => e.Mode(GridEditMode.Popup)
.AllowUpdating(false)
.AllowAdding(false)
.AllowDeleting(false)
.UseIcons(true)
.Popup(p => p
.ShowTitle(true)
.Width(700)
.Height(525)
)
.Form(f => f.Items(items =>
{
items.AddGroup()
.Caption("Detail Group Quota")
.ColCount(2)
.ColSpan(2)
.Items(groupItems =>
{
groupItems.AddSimpleFor(m => m.GroupQuotaId).Visible(false);
groupItems.AddSimpleFor(m => m.SitePlan);
groupItems.AddSimpleFor(m => m.Description);
});
items.AddGroup()
.Caption("Principal")
.ColCount(2)
.ColSpan(2)
.Items(groupItems =>
{
groupItems.AddSimpleFor(m => m.Principal).Template(new TemplateName("EmbeddedDataGridMultiple")).ColSpan(2);
});
}))
)
)

Custom Max aggregate on a Date column in kendo grid

I am trying to perform a custom max aggregate on a date column in a kendo grid and display it using the ClientFooterTemplate at the bottom of the column. I want to calculate the max aggregate only when all dates under the date column have values.
#(Html.Kendo().Grid<InstallerWrapper>().Name(#"InstallerTable")
.DataSource(dataSource => dataSource
.Ajax()
.Model(m => m.Id(o => o.InstallerId))
.Read(read => read
.Action("GetInstaller", "DataProvider", new { orderId = Model.OrderId })
.Type(HttpVerbs.Post))
.Aggregates(aggregates =>
{
aggregates.Add(o => o.SurveyReceivedDate).Max();
})
.PageSize(20)
)
.Columns(columns =>
{
columns.Bound(o => o.InstallerId).Title("Installer")
.ClientTemplate("#=VendorName#")
.Filterable(false).Width(225)
.ClientFooterTemplate("All")
.Sortable(false);
columns.Bound(o => o.SurveyReceivedDate).Title("Survey Received")
.HeaderHtmlAttributes(new { style = "overflow: visible; white-space: normal" })
.Filterable(false)
.ClientTemplate("#=SurveyReceivedDate#")
.ClientFooterTemplate("#=kendo.toString(kendo.parseDate(max),'MM/dd/yyyy')#")
.Sortable(false);
})
.Selectable()
.Sortable()
.Filterable()
.Pageable(p => p.Refresh(true)))
Use a function in the ClientFooterTemplate for the column to get this.
columns.Bound(o => o.SurveyReceivedDate).Title("Survey Received").HeaderHtmlAttributes(new { style = "overflow: visible; white-space: normal" }).Filterable(false)
.ClientTemplate("#=SurveyReceivedDate#")
.ClientFooterTemplate("#if (getMaxDateText()){# #} else{# #=kendo.toString(kendo.parseDate(max),'MM/dd/yyyy')# #} #")
.FooterHtmlAttributes(new { style =" color: red "})
.Sortable(false);
Javascript Function:
<script>
function getMaxDateText() {
var surveyReceivedArray = [];
var data = $("#InstallerTable").data("kendoGrid").dataSource._data;
for (var i = 0; i < data.length; i++) {
surveyReceivedArray.push(data[i].SurveyReceivedDate);
}
var isAtLeastOneNull = surveyReceivedArray.some(function (o) { return o === null; });
if (isAtLeastOneNull) {
return true;
}
else {
return false;
}
}
</script>

How to pass object as parameter to kendo grid read method

I have kendo grid as follow.
#(Html.Kendo().Grid<ManualInputDetail>()
.Name("gManualInputDetail")
.Columns(columns =>
{
columns.Bound(c => c.Id).Hidden(true);
columns.Bound(c => c.Month).Title("Month");
columns.Bound(c => c.Value).Title("Value");
})
.Editable(editable => editable.Mode(GridEditMode.InLine))
.Pageable()
.Navigatable()
.Selectable(selectable =>
{
selectable.Mode(GridSelectionMode.Single);
selectable.Type(GridSelectionType.Row);
})
.Sortable(sortable =>
{
sortable.SortMode(GridSortMode.MultipleColumn);
})
.DataSource(dataSource => dataSource
.WebApi()
.Model(model => model.Id(p => p.Id))
.PageSize(12)
.Read(read => read.Url(Url.HttpRouteUrl("ActionApi", new { controller = "ManualInputDetails", action = "GetManualInputDetails" })).Data("getFilterData"))
)
.Pageable(p => p.Refresh(true))
)
using getFilterData function I want to pass object parameter to read method. getFilterData function as follow
function getFilterData() {
var header= {
SectorId: 1,
BrandId: 2,
LocationId: 1,
DataElementId:2
}
return {
header: header
};
}
GetManualInputDataElements method as follow
[ActionName("GetManualInputDetails")]
public DataSourceResult GetManualInputDetails([System.Web.Http.ModelBinding.ModelBinder(typeof(WebApiDataSourceRequestModelBinder))] DataSourceRequest request,ManualInputHeader header)
{
var model = new DataElementMgt().GetAll(header).Select(x => new DataElement()
{
Id = x.Id,
DataElementTypeId = x.DataElementTypeId,
Name = x.Name,
Descriptionn = x.Descriptionn
}).ToList().ToDataSourceResult(request);
return model;
}
In here header value always gives as null. What is the reason for that. Is any thing wrong? Please help..
change the getFilterData method to this
function getFilterData() {
var _header= {
SectorId: 1,
BrandId: 2,
LocationId: 1,
DataElementId:2
}
return {
header: _header
};
}
and it should work. dont use the same name for what you return and declare.

Populating ASP.NET MVC Kendo Grid Via Ajax Call

I have an MVC Kendo Grid and I want to fill it via a jQuery Ajax Call. I used jQuery 'each' method to do it like this :
function FillRowsByRequest(reqRow) {
var readDataUrl = '#Url.Action("GetGoodsByReq")';
var targetGrid = $("#storeReceiptRowsGrid").data("kendoGrid");
$.get(readDataUrl, { reqseq: reqRow }, function (d, t, j) {
var counter = 0;
targetGrid.cancelChanges();
$(d).each(function (i, e) {
targetGrid.dataSource.insert(counter++, {
GOOD_ID: e.GOOD_ID,
GOOD_CODE: e.GOOD_CODE,
GOOD_CODE_DESC: e.GOOD_CODE_DESC,
GOOD_DESC: e.GOOD_DESC
});
});
});
}
I can see my Kendo Grid that is filled with data ( not completely ) but the thing is that when I click on the Save button, it does not trigger the Save Action Method and consequently nothing is inserted in the table and Grid contains nothing after it is refreshed.
#(Html.Kendo()
.Grid<Tpph.Models.STORE_RECEIPT_ROW>()
.Name("storeReceiptRowsGrid")
.Columns(columns =>
{
columns.Bound(o => o.GOOD_ID).Title("Good ID").HtmlAttributes(new { #class = "goodid" }).Visible(false);
columns.Bound(o => o.GOOD_CODE).Title("Good Code").HtmlAttributes(new { #class = "goodcode" }).Width(100);
columns.Bound(o => o.GOOD_CODE_DESC).Title("Good Code Desc").HtmlAttributes(new { #class = "goodcodedesc" }).Width(100);
columns.Bound(o => o.GOOD_DESC).Title("Good Desc").HtmlAttributes(new { #class = "gooddesc" }).Width(155);
})
.ToolBar(toolbar =>
{
toolbar.Create().Text("New Row").HtmlAttributes(new { #class = "k-primary", style = "background-color: #e6ffe6; border-color: #10c4b2; min-width: 100px; color: black;" });
toolbar.Save().Text("Save").SaveText("Save").CancelText("Cancel").HtmlAttributes(new { #class = "k-primary", style = "background-color: #e6ffe6; border-color: #10c4b2; min-width: 100px; color: black;" });
})
.ColumnMenu()
.Selectable(s => s.Type(GridSelectionType.Row))
.Sortable()
.Editable(editable => editable.Mode(GridEditMode.InCell).DisplayDeleteConfirmation("Delete?"))
.Filterable()
.Groupable()
.Scrollable()
.Pageable(p => p.Refresh(true))
.Resizable(resize => resize.Columns(true))
.Reorderable(reorder => reorder.Columns(true))
.DataSource(dataSource => dataSource
.Ajax()
.Events(ev => ev.RequestEnd("storeReceiptRowsGridOnRequestEnd"))
.Batch(true)
.ServerOperation(true)
.Model(model =>
{
model.Id(p => p.GOOD_ID);
})
.Read(read => read.Action("StoreReceiptRowsRead", "StorageForms"))
.Update(u => u.Action("StoreReceiptRowsEdit", "StorageForms"))
.Create(c => c.Action("StoreReceiptRowsCreate", "StorageForms"))
.Destroy(de => de.Action("StoreReceiptRowsDestory", "StorageForms")))
.Events(ev =>
{
ev.DataBound("storeReceiptRowsGridOnBound");
})
)
How can I do this ?
After lots of struggling with this issue, I finally found out that the Kendo Grid triggers the CRUD Action Methods only when the "dirty" attribute of a row is set to true. ( dirty flag is a tiny little red triangle which appears in the corner of a cell when you edit that cell ). So the solution to this issue is setting dirty flag of each row to true like this :
.set("dirty", true);
So my final JavaScript Code is like this :
function FillRowsByRequest(reqRow) {
var readDataUrl = '#Url.Action("GetGoodsByReq")';
var targetGrid = $("#storeReceiptRowsGrid").data("kendoGrid");
$.get(readDataUrl, { reqseq: reqRow }, function (d, t, j) {
var counter = 0;
targetGrid.cancelChanges();
$(d).each(function (i, e) {
targetGrid.dataSource.insert(counter++, {
GOOD_ID: e.GOOD_ID,
GOOD_CODE: e.GOOD_CODE,
GOOD_CODE_DESC: e.GOOD_CODE_DESC,
GOOD_DESC: e.GOOD_DESC
}).set("dirty", true);
});
});
}

My kendo grid is duplicating records

I have a kendo gri in my application.
Here's a picture of it.
And here's the code
#(Html.Kendo().Grid<TekstenViewModel.Tekst>()
.Name("Grid")
.Columns(columns =>
{
columns.Template(#<text></text>).ClientTemplate("<input type='checkbox'/>").Width(10).Hidden(!Model.Administrator);
columns.Bound(product => product.RESOURCE_SET_NAAM).ClientTemplate("#= RESOURCE_SET_NAAM#");
columns.Bound(product => product.Naam).ClientTemplate("#= Naam#");
columns.Bound(product => product.Waarde).ClientTemplate("<div id='editorDiv'><div class='input'>#if(Waarde){# #if(Waarde.length>100){# # var myContent =Waarde; # # var dcontent = myContent.substring(0,100); # <span>#=kendo.toString(dcontent)#</span> #}else{# <span>#=Waarde#</span> #}# #}#</div><div class='editor'>" +
Html.WebCore().LinkButton(type: ButtonType.Edit, htmlAttributes: new { onclick = "openPopupDemo('#: Waarde #', '#: ID #', 'Waarde')" }));
columns.Bound(product => product.Opmerking).ClientTemplate("<div id='editorDiv'><div class='input'>#if(Opmerking){# #if(Opmerking.length>100){# # var myContent =Opmerking; # # var dcontent = myContent.substring(0,100); # <span>#=kendo.toString(dcontent)#</span> #}else{# <span>#=Opmerking#</span> #}# #}#</div><div class='editor'>" +
Html.WebCore().LinkButton(type: ButtonType.Edit, htmlAttributes: new { onclick = "openPopupDemo('#: Opmerking #', '#: ID #', 'Opmerking')" }));
columns.Template(#<text></text>).ClientTemplate("<div id='deleteDiv'><div class='delete'><a class=\"delete iconBtn\" onclick=\"deleteResourceItem(#: ID #, '#: Naam #')\"></a></div></div>").Width(10).Hidden(!Model.Administrator);
})
.Pageable()
.Sortable()
.Filterable()
.Events(events => events.Edit("onCellEdit").DataBinding("onDataBinding").DataBound("onDataBound"))
.Groupable()
.Resizable(a => a.Columns(true))
.Navigatable()
.Editable(editable => editable.Mode(GridEditMode.InCell).DisplayDeleteConfirmation(false))
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.Events(e => e.Error("error_handler"))
.Model(model =>
{
model.Id(product => product.ID);
model.Field(product => product.Naam).Editable(Model.Administrator);
model.Field(product => product.Opmerking).Editable(Model.Administrator);
model.Field(product => product.Waarde).Editable(!Model.ReadOnly);
model.Field(product => product.RESOURCE_SET_ID).DefaultValue(Model.SetID);
model.Field(product => product.Type).DefaultValue(Domain.Agromilieu2.Common.Objects.Entities.Resources.ResourceType.GLOBAL_RESOURCES);
model.Field(product => product.Taal).DefaultValue(Domain.Agromilieu2.Common.Agromilieu2Constants.Resources.DEFAULT_TAAL_CODE);
})
.Create(create => create.Action(MVC.BeheerTeksten.ActionNames.ResourceItems_Create, MVC.BeheerTeksten.Name).Data("onCreateAdditionalData"))
.Read(read => read.Action(MVC.BeheerTeksten.ActionNames.ResourceItems_Read, MVC.BeheerTeksten.Name, new { setID = Model.SetID }).Data("onReadAdditionalData"))
.Update(update => update.Action(MVC.BeheerTeksten.ActionNames.ResourceItems_Update, MVC.BeheerTeksten.Name).Data("onAdditionalData"))
.Destroy(destroy => destroy.Action(MVC.BeheerTeksten.ActionNames.ResourceItems_Delete, MVC.BeheerTeksten.Name))
)
)
The grid works just fine, except when I create a new record. It calls the method to create, saves the record on the database, etc, no problem.
But when I return to the view, the record I just add appears as a duplicate of the first record inserted in the table.
Yes, I know it sounds strange but it's true. I've tried several times with different values, but I always get the same result.
Every new record is shown as a duplicate of the first record added to the grid. Off course, if I refresh the page, the data is correct.
Here's an example.
The grid before adding a new record.
The grid after inserting a new record.
Finally, after saving changes, I get this. If I refresh the page, the data is correct.
And here's my create method.
[AcceptVerbs(HttpVerbs.Post)]
[Domain.BasisArchitectuur.Framework.MVC.ActionFilters.MenuItem("Teksten")]
[IsAgromilieuActieAllowed(ActieClaims.TekstenBeheren)]
public virtual ActionResult ResourceItems_Create([DataSourceRequest]DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<TekstenViewModel.Tekst> resourceItems, long setID, string toepassingsCode)
{
List<ResourceItemDto> entities = new List<ResourceItemDto>();
if (ModelState.IsValid && SecurityHelper.IsActieAllowed(ActieClaims.TekstenBeheren))
{
try
{
using (IProxy<IResourceService> proxy = _proxyFactory.Create<IResourceService>())
{
foreach (TekstenViewModel.Tekst tekstenViewModel in resourceItems)
{
ResourceItemDto resourceItem = new ResourceItemDto
{
ResourceItem_ID = tekstenViewModel.ID,
ResourceSet_ID = setID,
Naam = HttpUtility.HtmlDecode(tekstenViewModel.Naam),
Opmerking = HttpUtility.HtmlDecode(tekstenViewModel.Opmerking),
Waarde = HttpUtility.HtmlDecode(tekstenViewModel.Waarde),
Type_Code = tekstenViewModel.Type,
Taal_Code = tekstenViewModel.Taal,
ResourceWaarde_ID = tekstenViewModel.WAARDE_ID
};
entities.Add(resourceItem);
}
proxy.Client.CheckIfNameExists(entities, toepassingsCode);
proxy.Client.AddOrUpdateResourceItem(entities.AsEnumerable());
}
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, ex.Message);
}
}
else
{
var errMsg = ModelState.Values
.Where(x => x.Errors.Count >= 1)
.Aggregate("Model State Errors: ", (current, err) => current + err.Errors.Select(x => x.ErrorMessage));
ModelState.AddModelError(string.Empty, errMsg);
}
resourceItems = GetResourceItemsList(new TekstenViewModel.ZoekCriteria { Taal = resourceItems.FirstOrDefault().Taal, ResourceSet_ID = resourceItems.FirstOrDefault().RESOURCE_SET_ID });
return Json(resourceItems.ToDataSourceResult(request, ModelState));
}
The problem should be that you are not returning a Json with product.ID back from your create action
Create(create => create.Action(MVC.BeheerTeksten.ActionNames.ResourceItems_Create, MVC.BeheerTeksten.Name).Data("onCreateAdditionalData"))
Need to Return , the added item with the model.Id(product => product.ID);
Kendo grid tracks the Items when created by the ID so you need to provide it back to the DataSource