kendo grid ,display links with client template - kendo-ui

// this is my kendo grid , in client template how to write DateTime nowDate = DateTime.Now; this things ...
//OrderList is my model class
#(Html.Kendo().Grid<MDA.AppEntities.Orders.OrderList(Model.OrderList)
//define the name of grid
.Name("GridLastOrder")
// adding column in kendo grid
.Columns(columns =>
{
columns.Bound(c => c.EventConsultStatusID).ClientTemplate(#
if (CustomerSource == "+3+" || CustomerSource == "+5+")
{#
DateTime nowDate = DateTime.Now;
TimeSpan spn = nowDate.Subtract(EventLastUpdated);
if (spn.Days > 2)
{#
Patient Picked-Up<br />
#}
# }
})
.Resizable(resizing => resizing.Columns(true))
.Pageable(Page => Page.Refresh(true).PageSizes(true).PreviousNext(true))
.Filterable()
.Sortable()
.Scrollable()
.Groupable()
.Reorderable(reorder => reorder.Columns(true))
.DataSource(dataSource => dataSource.Ajax()
.ServerOperation(false)
)
)

Inside the client template you can write only JS code, C# code is not supported

Related

Telerik Grid MVC not displaying data on read

So I've got a grid that I believe is all set up correctly. I've confirmed that the data is coming through, and I've even checked that the AJAX call returns a success with the "ToDataSourceResult" JSON data.
​
Unfortunately, the only problem is that the data doesn't display. This seems to only be an issue on read, as update, create and delete all work. Just can't retrieve the list of all items afterwards.
​
My controller action looks like this:
public IActionResult Blog_Read([DataSourceRequest] DataSourceRequest request)
{
var blogs = _blogService.GetPosts().Select(post => new BlogPostModel
{
Id = post.Id,
Title = post.Title,
Author = post.Author,
ShortDescription = post.ShortDescription,
Contents = post.Contents,
LastSaved = post.LastSaved,
Published = post.Published,
PublishedOn = post.PublishedOn
});
var result = blogs.ToDataSourceResult(request);
return Json(result);
}
​
And my Grid View looks like this:
#(Html.Kendo().Grid<BlogPostModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.Title);
columns.Bound(p => p.Author).Width(120);
columns.Bound(p => p.LastSaved).Width(120);
columns.Bound(p => p.Published).Width(120);
columns.Command(command => { command.Edit(); command.Destroy(); }).Width(250);
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.PopUp))
.Pageable()
.Sortable()
.Scrollable()
.HtmlAttributes(new { style= "height:600px;"})
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Events(events => events.Error("error_handler"))
.Model(model => model.Id(p => p.Id))
.Create(update => update.Action("Blog_Create", "BlogAdmin"))
.Read(read => read.Action("Blog_Read", "BlogAdmin"))
.Update(update => update.Action("Blog_Update", "BlogAdmin"))
.Destroy(update => update.Action("Blog_Delete", "BlogAdmin"))
)
.Deferred()
)
​
The correct JSON is returned, no javascript errors in the console, so I'm a little confused as to what this could be. Any help would be greatly appreciated.
I solved this by adding
services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
to my Startup.cs ConfigureServices method.

Dynamically limit date range in Kendo Grid MVC date column

I'm trying to set a min and max values for datetime picker control inside a grid. The value needs to be set dynamically, based on the value of another datepicker on the form.
I had try handling the onEdit event and trying to find the datetime picker control inside the row been edited to set those values without looking.
Whats is the proper way of restricting date ranges in Kendo Grid MVC inline editing?
This is how the grid is created:
<div>
#(Html.Kendo().Grid<CpcPrevisionUnidadesDto>()
.Name("gridListado")
.HtmlAttributes(new { #class = "kendo-grid-" })
.AutoBind(false)
.Columns(columns =>
{
columns.Bound(c => c.IdCpcPrevisionParadasUnidadesDto).Hidden();
columns.Bound(c => c.IdCpcUnidadesProceso).Hidden();
columns.Bound(c => c.CodigoUnidadProceso).Title(Html.Resource("CPC_CU_DP003_Unidad").ToString());
columns.Bound(c => c.DescripcionUnidadProceso).Title(Html.Resource("CPC_CU_DP003_Nombre").ToString());
columns.Bound(c => c.FechaParada).Title(Html.Resource("CPC_CU_DP003_FechaParada").ToString()).Format("{0:dd/MM/yyyy}").EditorTemplateName("Date"); // Need to set MAX and MIN values
columns.Bound(c => c.FechaArranque).Title(Html.Resource("CPC_CU_DP003_FechaArranque").ToString()).Format("{0:dd/MM/yyyy}").EditorTemplateName("Date"); // Need to set MAX and MIN values
columns.Bound(c => c.Observaciones).Title(Html.Resource("CPC_CU_DP003_Observaciones").ToString());
columns.Template(c => { }).Title(" ").Width(40).ClientTemplate("#=menuRuedaTemplate([uid])#").HtmlAttributes(new { style = "overflow: visible;" });
})
.DataSource(datasource => datasource
.Ajax()
.PageSize(20)
.Read(read => read.Action("BuscarPrevisionParadasPrevistasUnidades", "PrevisionParadasPrevistasUnidades").Data("setParametrosListado"))
.Create(create => create.Action("CreatePrevisionParadasPrevistasUnidades", "PrevisionParadasPrevistasUnidades").Type(HttpVerbs.Post).Data("sendAntiForgery"))
.Update(update => update.Action("UpdatePrevisionParadasPrevistasUnidades", "PrevisionParadasPrevistasUnidades").Type(HttpVerbs.Post).Data("sendAntiForgery"))
.Sort(sort => sort.Add("CodigoUnidadProceso").Ascending())
.Events(e => e.Error("screenErrorHandling"))
.Model(model => model.Id(p => p.IdCpcPrevisionParadasUnidadesDto))
)
.Sortable()
.Navigatable()
.Pageable(pager => pager.Messages(messages => messages.Display(Html.Resource("Mensaje_Grid_Datos").ToString()))
.Messages(m => m.Empty(Html.Resource("Mensaje_Grid_SinDatos").ToString())))
.Resizable(r => r.Columns(true))
.Events(e => e.DataBound("dataBoundGrid").Edit("onEdit"))
.Editable(editable => editable.Mode(GridEditMode.InCell))
.ToolBar(toolbar => toolbar.Save().SaveText(Html.Resource("MAIN_Guardar").ToString()).CancelText(Html.Resource("MAIN_Cancelar").ToString())))
</div>
This is the date editor template:
#model DateTime?
#(Html.Kendo().DatePickerFor(m => m))
You need to edit the HTML for your DatePicker and specify values for Min and Max. In this example, you will only be able to choose past values from this year.
#(Html.Kendo().DatePickerFor(m => m)
.Min("01/01/2016")
.Max(DateTime.Now)
)
If you need to set the value dynamically, you can try this, just get the value you need:
$("#Date").data("kendoDatePicker").min(new Date(2015, 0, 1))
same for .max()
Try that on your "onEdit" event, when the datepicker is created, and let me know if you need more help

MVC: get uploaded filename back in grid column

I have an MVC razor form with a Kendo grid. The grid has an asynch image uploader.
#(Html.Kendo().Grid<CraftStore.Models.Catalog>()
.Name("CatalogGrid")
.Columns(columns =>
{
columns.Bound(p => p.CatalogName).Filterable(true).Width(240);
columns.Bound(p => p.CatalogDescription).Filterable(true).Width(340);
columns.Bound(p => p.ModelNumber).Filterable(true).Width(110);
columns.Bound(p => p.SerialNumber).Filterable(true).Width(110);
columns.Bound(p => p.InventoryCount).Filterable(true).Width(110);
columns.Bound(p => p.WebPrice).Title("Price").Format("{0:C}").EditorTemplateName("Currency").Width(110);
columns.Bound(p => p.ImagePath).ClientTemplate("<img height='80' src='" + Url.Content("~/Content/Images/catalog/Products/") + "#=data.ImagePath#' title='#=data.ImagePath#' alt='#=data.CatalogName#' />").EditorTemplateName("Image").Title("Picture").Width(300);
columns.Command(command => command.Destroy()).Width(110);
})
.ToolBar(toolbar =>
{
toolbar.Create();
toolbar.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Filterable(filterable => filterable
.Extra(false)
.Operators(operators => operators
.ForString(str => str.Clear()
.Contains("Contains")
.StartsWith("Starts with")
.IsEqualTo("Is equal to")
.IsNotEqualTo("Is not equal to"))
.ForNumber(num => num.Clear()
.IsEqualTo("Is equal to")
.IsNotEqualTo("Is not equal to")
.IsGreaterThan("Greater than")
.IsLessThan("Greater than"))
))
.Navigatable()
.Selectable(selectable => selectable.Type(GridSelectionType.Row))
.Scrollable(scrollable =>
{
scrollable.Virtual(true);
scrollable.Height(400);
})
.Events(events =>
{
events.Change("change");
})
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.PageSize(20)
.Model(model =>
{
model.Id(p => p.Id);
}
)
.Events(events =>
{
events.Error("error_handler");
})
.Create("CatalogEditing_Create", "WebCatalog")
.Read("CatalogEditing_Read", "WebCatalog")
.Update("CatalogEditing_Update", "WebCatalog")
.Destroy("CatalogEditing_Destroy", "WebCatalog")
)
)
All work fine! - the image has a tooltip of the filename...
The upload and remove work great...
I have an edit template for image (image.cshtml in Views/Shared/EditorTemplates)
The template is:
#model string
<div style="width:100%">
<div class="section">
#Html.TextBoxFor(model => model, new {#class="k-textbox result-box" })
#(Html.Kendo().Upload()
.Name("files")
.Events(events=>events.Success("OnUploadSuccess"))
.Multiple(false)
.Async(a => a
.Save("Save", "Upload")
.Remove("Remove", "Upload")
.AutoUpload(true)
)
)
</div>
</div>
The OnUploadSuccess js function (which is defined on the razor view) has the success function
<script type="text/javascript">
//file upload scripts
function getFileInfo(e) {
return $.map(e.files, function (file) {
var info = file.name;
// File size is not available in all browsers
if (file.size > 0) {
info += " (" + Math.ceil(file.size / 1024) + " KB)";
}
return info;
}).join(", ");
}
function OnUploadSuccess(e) {
$(".result-box").value = getFileInfo(e);
Model = getFileInfo(e);
}
all works fine - the variable 'Model' does get the correct filename.
Now...
How do I get that filename value returned by getFileInfo(e) to be the current value for the grid column???
I thought 'Model' would work, but it does not.
Model = getFileInfo(e);
//since this is in a template, I thought it would bind 'Model' to the column
Then, you can see above, in OnUploadSuccess, I also thought it could be done by using jQuery :
$(".result-box").value = getFileInfo(e);
The jQuery does find and set the value, but the row's member named ImagePath never gets the resulting value.
Neither work, and I'm not sure how to get the returned filename to be the column value.
Any help appreciated.
UPDATE:
Well, I've updated the OnUpdateSuccess js function:
var fn = getFileName(e);
$("#ImagePath").val(fn)
And this now updates the field - but this is not saving when you tab out of the field or immediately hit save. In either care, the old value is restored.
How do I get it to stay? I imagine this is where the MVVM binding will help?
After working with the amazing support from Telerik, I was right - it's a binding issue because the MVVM doesn't know about my change. To get it to know about my change I need to add a line after the script change above:
$("#ImagePath").trigger("change");
Now, it works perfectly!

Kendo UI Grid batch delete

I have Kendo Grid with delete command. When I click delete and then click "save change" on the left top of grid, real data is not sent to server. data has key/create date/other fields. I used Odata service. In debug mode, key = 0 and create date = 1/1/0001. Anyone got a clue what is happening here?
#(Html.Kendo().Grid<OData.proxySvc.table1>()
.Name("MyGrid")
.Columns(columns =>
{
columns.Bound(f => f.key).Visible(false);
columns.Bound(f => f.UserName).Title("Name");
columns.Command(command => {
command.Destroy();
}).Title("Action").Width(90);
})
.ToolBar(toolbar =>
{
toolbar.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Sortable()
.Scrollable(s => s.Height("100px"))
.Filterable()
.DataSource(ds => ds
.Ajax()
.Batch(true)
.ServerOperation(false)
.Model(model => model.Id(p => p.key))
.Destroy("Delete","Home")
))
in control file, there is action:
// no [Httppost] attributes. if [HttpPost] attributes exist, no event fire
public ActionResult Delete([DataSourceRequest]DataSourceRequest request,
[Bind(Prefix = "models")]IEnumerable<table1> tbl1)
{
var context = CreateOdataServiceContext();
foreach (var t1 in tbl1)
{
var x = context.table1.Where(r => r.key == t1.key).FirstOrDefault();
if (x!=null)
{
context.DeleteObject(x);
context.SaveChanges();
}
}
}

Kendo UI Grid Hide Column.Template

The components I'm using Kendo UI, but I have problem in Grid
If you use the code below the column "Command" does not show on the page, but the page Change Sort or by grid, there is a page refresh.
#(Html.Kendo().Grid(Model)
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.cd_empresa).Visible(false);
columns.Bound(p => p.cd_grupo).Visible(false);
columns.Bound(p => p.descricao);
columns.Template
(
#<text>
Text 1
Text 2
</text>
).Title("Command").Width(80);
})
.ColumnMenu()
.Selectable(selectable => selectable.Mode(GridSelectionMode.Single))
.Pageable()
.Sortable()
.Scrollable(scr => scr.Height(240))
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(false)
.PageSize(7)
.Read(read => read.Action("Index", "GrupoFiscal"))
.Model(model => model.Id(p => p.cd_grupo))
.Model(model => model.Id(p => p.cd_empresa))
)
)
If I put
    
. DataSource (dataSource => dataSource
         . Ajax ()
         . ServerOperation (false)
         . PageSize (7)
         . Read (read => read.Action ("Index", "GrupoFiscal"))
         . Model (model => model.Id (p => p.cd_grupo))
         . Model (model => model.Id (p => p.cd_empresa))
     )
Ajax works without refresh the page, but the column "Command" no shows.
Note This column has links to Edit, Delete and Details
Refer to the documentation:
A column template is not displayed
This will happen if the server template is set but the grid is
configured for ajax binding. Set the ClientTemplate as well. This will
also happen if only the client template is set but the grid is
configured for server binding. Set the Template as well.

Resources