Kendo UI Grid different detail templates depending on condition - c#

I have such grid defined
#(Html.Kendo().Grid<FieldViewModel>(Model.Fields)
.HtmlAttributes(new { #class = "fullScreen" })
.Name("formFields")
.ClientDetailTemplateId("formFieldsTemplate")
.Columns(columns =>
{
columns.Bound(e => e.Key);
columns.Bound(e => e.DisplayName);
columns.Bound(e => e.FieldTypeName);
columns.Bound(e => e.Order);
columns.Bound(e => e.IsMandatory);
columns.Bound(e => e.Type);
})
.Pageable()
.Sortable()
.Scrollable()
.Selectable()
.Resizable(resize => resize.Columns(true))
.Groupable()
.Filterable()
.DataSource(dataSource => dataSource.Ajax().ServerOperation(false).Model(model => model.Id(e => e.Key))))
and details template
<script id="formFieldsTemplate" type="text/kendo-tmpl">
#(Html.Kendo().Grid<FieldViewModel>()
.Name("FormField_#=Key#")
.ClientDetailTemplateId("formFieldsTemplate")
.Columns(columns =>
{
columns.Bound(e => e.Key);
columns.Bound(e => e.DisplayName);
columns.Bound(e => e.FieldTypeName);
columns.Bound(e => e.Order);
columns.Bound(e => e.IsMandatory);
columns.Bound(e => e.Type);
})
.DataSource(dataSource => dataSource.Ajax().Read(read => read.Action("LoadFieldDetails", "Forms", new { formPath = Model.Schema, rootElementName = Model.Root ,fieldKey = "#=Key#" })))
.Pageable()
.Sortable()
.Selectable()
.ToClientTemplate())
</script>
As you can see I have Type property (of type int), so what I want to do is not to show any details view and no arrow on the entire row when Type property is set to the specific value. How can I achieve it?

When you define your template like this, then it's used on client side. It's rendered by the #(Html.Kendo().Grid<FieldViewModel>() command but actually then used on client side. But you cannot compare a Type on clientside. but for example, when constructing the model you do:
if (myType is MyDataType) // Do the type check
{
myRow.UseTemplate = 1; // Define ID for template
}
else // ...and so on, can do a 'switch` or whatever
{
myRow.UseTemplate = 2;
}
And here is your template where you switch by Template ID:
<script id="formFieldsTemplate" type="text/kendo-tmpl">
# if (UseTemplate == 1) { #
<div>Template 1</div>
# } else { #
<div>Template 2</div>
# } #
</script>
Not sure if it will work properly if you have different data to display within your data rows... Hope you get the idea though.

Related

Why Kendo MVC Grid export excel function hiding all columns in excel file?

I have kendo mvc grid and basically all functions are correct but when i try to export my excel from my grid it's downloading excel but hiding all columns results weirdly
Here my grid
#(Html.Kendo().Grid<Alerts>()
.Name("grdWaterAlert").AutoBind(false)
.HtmlAttributes("width: 100%;cellpadding:0;")
.DataSource(d => d.Ajax().Read("GridWaterAlertBinding", "Dashboards"))
.Columns(columns =>
{
columns.Bound(e => e.BelIdent).Title("Id").Width("auto");
columns.Bound(e => e.StationCode).Title("Station Code").Width("auto");
columns.Bound(e => e.StationName).Title("Station Name").Width("auto");
columns.Bound(e => e.BelTarih).Title("DateTime").ClientTemplate("#= kendo.toString(BelTarih, 'MM/dd/yyyy') #").ClientGroupHeaderTemplate("DateTime" + ": #= kendo.toString(value, 'MM/dd/yyyy') #").Width("auto");
columns.Bound(e => e.BelInsTime).Title("Alert Time").ClientTemplate("#= kendo.toString(BelInsTime, 'MM/dd/yyyy HH:mm tt') #").ClientGroupHeaderTemplate("DateTime" + ": #= kendo.toString(value, 'MM/dd/yyyy HH:mm tt') #").Width("auto");
columns.Bound(e => e.BelTankId).Title("Tank ID").Width("auto");
columns.Bound(e => e.ProductCode).Title("Product Code").Width("auto");
columns.Bound(e => e.BelAlarm).Title("Alarm").Width("auto");
columns.Bound(e => e.BelTotCapacity).Title("Total Capacity").Width("auto");
columns.Bound(e => e.BelWaterVol).Title("Water Volume").Width("auto");
})
.ToolBar(toolBar =>
{
toolBar.Excel().HtmlAttributes(new { #class = "btnexcel" }).Text(" ").IconClass("k-i-excel");
toolBar.Custom().Text((string)ViewData["ClearFilter"]).HtmlAttributes(new { #class = "k-button", id = "cleargrid", href = "#", onclick = "clearFiltersWaterLevel()" });
})
.Excel(excel => excel.FileName("WaterAlert.xlsx").Filterable(true))
.Selectable()
.Sortable()
.AutoBind(false)
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5))
.Filterable(filterable => filterable
.Extra(false)
.Operators(operators => operators
.ForString(str => str.Clear()
.StartsWith((string)ViewData["Startswith"])
.Contains((string)ViewData["Contains"])
))
)
.Groupable()
.Scrollable(scrolling => scrolling.Height("100%"))
.Resizable(config =>
{
config.Columns(true);
})
.Reorderable(config =>
{
config.Columns(true);
})
.ColumnMenu()
)
How can i handle this problem?
I solved my problem myself i realised i gave all columns .Width("auto") and when Excel try to export grid checking column width and because of the .Width("auto") it cannot give automatic width than looks columns hide....
When i give width value everything looks perfect

In Kendo MVC Grid, how can I use local values for grid initialisation then later use the read operation?

I have the initial values for the grid in my ViewModel. But if the user wants to update values, I want to update my database, then send back the updated values for the grid from the backend. The problem is that the Ajax Read is always called. But it shouldn't because the (initial) values are there in the ViewModel and bound to Grid.
I tried setting the AutoBind to false, but it does not work, I get an error. (Cannot set AutoBind if widget is populated during initialization)
#(Html.Kendo().Grid<MyClass>()
.Name("MyClassGrid")
.BindTo(Model.MyClassList)
.Columns(column =>
{
column.Bound(c => c.SomeProp).Title("Some Property");
})
.Scrollable()
.DataSource(ds => ds
.Ajax()
.Read(read => read.Action("GetMyData", "CheckBar", new { param1 = Model.ParamFirst}))))
I want to display the already stored values for my grid, and only use the read operation if I want to update the values in my database too.
#(Html.Kendo().Grid<SQDCDashboard.Core.ViewModels.SafetyIncidentViewModel>()
.Name("safetyincident-grid")
.Columns(columns =>
{
columns.Bound(c => c.CreatedAt).HtmlAttributes(new { style = "width: 22%" }).Format("{0:MM/dd/yyyy}");
columns.Bound(c => c.Type).HtmlAttributes(new { style = "width: 22%" });
columns.Bound(c => c.Description).HtmlAttributes(new { style = "width: 22%" });
columns.ForeignKey(c => c.ProductionLineId, (System.Collections.IEnumerable)ViewData["ProductionLines"], "Id", "Name").HtmlAttributes(new { style = "width: 22%" });
columns.Command(command => { command.Edit(); }).HtmlAttributes(new { style = "width: 12%" });
})
.ToolBar(toolbar => toolbar.Create().Text("New Safety Incident"))
.Editable(editable => editable.Mode(GridEditMode.InLine))
.DataSource(ds =>
ds.Ajax()
.ServerOperation(false)
.Model(model =>
{
model.Id(p => p.Id);
model.Field(p => p.ProductionLineId).DefaultValue(Model.DefaultProdLine);
})
.Read(read => read.Action("GetSafetyIncidentList", "Safety"))
.Update(update => update.Action("EditSafetyIncidentInLine", "Safety"))
.Create(create => create.Action("CreateNewSafetyIncident", "Safety"))
)
.HtmlAttributes(new { style = "height: 100%" })
.Sortable()
.Filterable()
.Pageable()
.Mobile()
)
Here is an example of my grid. The Update(update => update.Action("Action" , "Controller"))
is the method you are wondering about. For my code I did not have to pass a parameter in with my read, and I do not need to pass one in with my Update.
[HttpPost]
public ActionResult EditSafetyIncidentInLine([DataSourceRequest] DataSourceRequest request, SafetyIncidentViewModel sivm)
{
if (sivm != null && ModelState.IsValid)
{
SafetyIncident si = _safetyIncidentService.Find(sivm.Id);
si.Description = sivm.Description;
si.ProductionLineId = sivm.ProductionLineId;
si.ProdLine = _productionLineService.Find(sivm.ProductionLineId);
si.Type = sivm.Type;
_safetyIncidentService.Update(si);
sivm.Id = si.Id;
sivm.CreatedAt = si.CreatedAt;
}
return this.Json(new[] { sivm }.ToDataSourceResult(request, ModelState));
}
This method is the one that is called when the Update button is pressed. The update button is created with the columns.Command(command => { command.Edit(); }; and the Editable(editable => editable.Mode(GridEditMode.InLine)). If you want more clarification or if your question is different let me know. I never got an error with having my grid already initialized when I was updating values.

Kendo UI MVC grid popup mode insert mode model.set not working for DropDownList

I have a sample like this popup editing mode
I want to store my model while first inserting, and set default values.
#(Html.Kendo().Grid<License>()
.Name("popupGrid")
.Columns(columns =>
{
columns.Bound(p => p.LicenseId).Width(20).Hidden().HeaderHtmlAttributes(new { #title = "License" });
columns.ForeignKey(p => p.CustomerId, (System.Collections.IEnumerable)ViewData["customers"], "CustomerID", "CustomerName")
.Title("Customer").Width(200);
columns.Bound(p => p.VendorId).Width(20).HeaderHtmlAttributes(new { #title = "Vendor" });
columns.Bound(p => p.ProductId).Width(20).HeaderHtmlAttributes(new { #title = "Product" });
columns.Command(p => p.Edit().Text("Edit").HtmlAttributes(new { #title = "Edit" })).Width(80);
})
.ToolBar(toolbar => toolbar.Create().HtmlAttributes(new {#id ="MyAddButton" ,#title = "Add" }))
.Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("PopupEditView"))
.Events(e => e.Edit("onGridEdit").Save("onGridSave"))
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(p => p.LicenseId))
.Create(create => create.Action("Create", "Home").Type(HttpVerbs.Post))
.Read(read => read.Action("Read", "Home").Type(HttpVerbs.Post))
.Update(update => update.Action("Update", "Home").Type(HttpVerbs.Post))
)
)
<script>
var myModel;
function onGridSave(e) {
if (e.model.isNew()) {
myModel = e.model;
}
}
function onGridEdit(e) {
if (e.model.isNew()&&myModel!=null) {
e.model.set("CustomerId", myModel.CustomerId);
e.model.set("VendorId", myModel.VendorId);
e.model.set("ProductId", myModel.ProductId);
}
}
</script>
But it's not working.
following code is not working too :
$(e.container).find('input[name="CustomerId"]').data("kendoDropDownList").value(myModel.CustomerId);//it's not giving error. but CustomerId is null in model of create method
Actually I want to this. But I don't know how to update datasource while prevent closing window.
You might try configuring your dropdownlist with valuePrimitive: true
http://docs.telerik.com/kendo-ui/api/javascript/ui/dropdownlist#configuration-valuePrimitive

Kendo UI Grid different templates for column based on its data type

I have such Grid
#(Html.Kendo().Grid(Model.Differences)
.Name("formDifferencesList")
.HtmlAttributes(new { #class = "fullScreen" })
.Columns(columns =>
{
columns.Bound(e => e.Property);
columns.Bound(e => e.FieldPath);
columns.Bound(e => e.FieldType);
columns.Bound(e => e.Type);
columns.Bound(e => e.LeftValue);
columns.Bound(e => e.RightValue);
})
.Pageable()
.Sortable()
.Scrollable()
.Selectable()
.Resizable(resize =>
resize.Columns(true))
.Groupable()
.Filterable()
.DataSource(dataSource =>
dataSource.Ajax()
.PageSize(25)
.ServerOperation(false)
.Model(model => model.Id(e => string.Format("{0}{1}", e.Property, e.FieldPath)))))
RightValue and LeftValue is instance of type Object, it can be primitive value (like int, string), but also it can be a collection. If it is a collection I want to use Kendo ListView to represent it. How should I do that?
I tried to bound to the DataBound event
.Events(events => events.DataBound("onDifferencesDataBounded"))
added ClientTemplate to the Grid
columns.Bound(e => e.LeftValue).ClientTemplate("<div class='leftValueView'></div>");
and then inside js function tried to apply the template
<script type="text/javascript">
function onDifferencesDataBounded() {
$.each($('.leftValueView'), function () {
var grid = $('#formDifferencesList').data().kendoGrid;
var row = $(this).closest('tr');
var dataItem = grid.dataItem(row);
$(this).kendoListView({
dataSource: { data: dataItem },
template: kendo.template($("#leftValueTemplate").html())
});
});
}
</script>
<script type="text/x-kendo-template" id="leftValueTemplate">
// Not sure what should I do here?
</script>
Is there anything at all in the dataItem.LeftValue or RightValue such as Array, when you put a breakpoint there?
var dataItem = grid.dataItem(row); // <-breakpoint when you pass that line
If there is array such as number array [1,3,4,5] then you can give a try to use #=data# inside of the template.

Can't see edit buttons in telerik grid

I'm creating a telerik grid as follows:
#{
GridEditMode mode = GridEditMode.InLine;
GridButtonType type = GridButtonType.Text;
Html.Telerik().Grid<testing.testtable>("testtable")
.Name("Grid")
.Pageable()
.Sortable()
.Filterable()
.Groupable()
.DataKeys(keys => keys.Add(c => c.intcolumn))
.DataBinding(dataBinding => dataBinding.Server()
.Insert("Insert", "HomeController", new { mode = mode, type = type })
.Update("Save", "HomeController", new { mode = mode, type = type })
.Insert("Delete", "HomeController", new { mode = mode, type = type }))
.Columns(columns =>
{
columns.Bound(o => o.intcolumn);
columns.Bound(o => o.stringcolumn);
})
.Editable(editing => editing.Mode(GridEditMode.InLine))
.Render();
}
From what I understand this should display an edit button but I don't see one in the table..
It's not enough to set the Editable option, you need to add the Edit command to your columns:
.Columns(columns =>
{
columns.Bound(o => o.intcolumn);
columns.Bound(o => o.stringcolumn);
columns.Command(commands => commands.Edit());
})
See the Telerik Demo site for more info.

Categories

Resources