I want to use Javascript Function in Kendo Grid Create.
For that I have defined the Javascript Function as,
<script>
function GetCompanyID()
{
return $("#Company").val();
}
</script>
And I want to use it in Create template of Kendo Grid as,
#(Html.Kendo().Grid<Invoice.Models.ViewModels.DossierViewModel>()
.Name("Dossier")
.Columns(columns =>
{
columns.Bound(p => p.CustomerName).Title("Customer").Width(150);
columns.Bound(p => p.InvoiceNumber).Title("INV no.").Width(100);//.Width(20);
columns.Bound(p => p.InvoiceAmountLC).Title("INV Amount LC").Width(150);
})
.ToolBar(toolbar => toolbar.Create().Text("Add New Dossier"))
.Editable(ed => ed.Mode(GridEditMode.PopUp).TemplateName("New_Dossier")) //Having Different Template for New Dossier
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
.Model(model => { model.Id(p => p.DossierID); })
.Read(read => read.Action("Dossier_Read", "Dossier"))
.Create(create => create.Action("Dossier_Create", "Dossier", new { #CompanyID = GetCompanyID }))
.Filter(filters =>
{
// Show products whose ProductName property contains "C"
filters.Add(dossier => dossier.Status).Contains("");
})
)
)
In that I want to use that Javascript functio as I am currently using in Above code as,
.Create(create => create.Action("Dossier_Create", "Dossier", new { #CompanyID = GetCompanyID }))
But this is not the Way it should be used. Please Help me on this. How can I use that Javascript function into this, ASAP.
You need to use the Data() method of the grid data source to send this data. Something like:
.Create(create => create.Action("Dossier_Create", "Dossier").Data("GetCompanyID")
function GetCompanyID()
{
return {
CompanyID: $("#Company").val();
};
}
Check the grid FAQ for more info and an example.
Related
I'm stuck in a problem, I have a grid that contains an item which can contain Json or XML. I need this data to be copied on the clipboard. Below is my code that i'm using to copy the content. It's basically setting the value of a hidden field and then copying the data from that field to the clipboard. What I'm stuck with is the data is being copied as a string and i want to have it copied in proper JSON formatting is there a way to achieve this? I have tried and none of these work.
JSON.stringify(jsObj, null, "\t");
JSON.stringify(jsObj, null, 4);
Below is the my copy function.
function CopyData(e) {
var tr = $(e.target).closest("tr");
var newItem = this.dataItem(tr);
$('#ContentTypeField').val(newItem.Content);
var copyText = document.getElementById("ContentTypeField");
copyText.type = 'text';
copyText.select();
copyText.setSelectionRange(0, 99999); /*For mobile devices*/
/* Copy the text inside the text field */
document.execCommand("copy");
copyText.type = 'hidden';
}
and my grid
#(Html.Kendo().Grid<App.Models.ViewModel>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.ID).Width(240).Hidden(true);
columns.Bound(p => p.Name).Width(280);2
columns.Bound(p => p.Description).Width(440);
columns.Command(command => {command.Custom("Content").Click("CopyData"); }).Width(150);
})
.ToolBar(toolbar =>
{
toolbar.Create().Text("Add");
})
.Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("Content.cshtml"))
.Pageable(pager => pager
.Input(true)
.Numeric(true)
.Info(true)
.PreviousNext(true)
.Refresh(true)
.PageSizes(true)
)
.Sortable()
.Reorderable(reorder => reorder.Columns(true))
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(true)
.Events(events => events.Error("error_AppSetting"))
.Model(model =>
{
model.Id(p => p.ID);
model.Field(s => s.Name);
model.Field(s => s.Description);
})
.Read("Read", "App")
.Update(c => c.Action("Update", "App"))
.Destroy(c => c.Action("Delete", "App"))
.Create(c => c.Action("Create", "App"))
)
)
I used clipboard API to achieve this. It takes the text as parameter since in the previous method I was setting value of a hidden field and then copying it to the clipboard which changed the formatting. Below is the code on how I did it.
navigator.clipboard.writeText(grid.fields.Content).then(function () {
alert('successfully copied!');
},
function () {
alert ('Copy to clipboard failed');
});
I am making a code using ASP.NET MVC with kendo grid.
I want to bring the data from database to Kendo grid which equal to specific date or by default "today".
I want to make a datepicker and a button at the toolbar and everytime I click the button it send a request to the control and filter the data in LINQ and send the request for all the data in one day. I wrote this code:
Controller class:
//main method
public ActionResult LogAdminList()
{
return View();
}
//submethod for grid
public ActionResult Grid_ReadLogAdminList([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "id")] string date)
{
DateTime _temp;
if (!DateTime.TryParse(date, out _temp))
_temp = DateTime.Now;
return Json(_context.Entities<LogAdmin>().NoTracking().OrderByDescending(l => l.TimeStamp)
.Where(f => DbFunctions.TruncateTime(f.TimeStamp) == DbFunctions.TruncateTime(_temp))
.Select(l => new LogAdminInfo
{
Id = l.Id,
Message = l.Message,
MessageTemplate = l.MessageTemplate,
Level = l.Level,
TimeStamp = l.TimeStamp,
Exception = l.Exception,
Properties = l.Properties,
LogEvent = l.LogEvent,
})
.ToDataSourceResult(request));
}
the kendo code is :
#(Html.Kendo().Grid<LogAdminInfo>()
.BindTo(Model)
.Name("LogAdminList")
.Sortable()
.Columns(columns =>
{
columns.Bound(p => p.Message).Width(50).Title(WebResources.LogListMessage);
columns.Bound(p => p.MessageTemplate).Width(50).Title(WebResources.LogListMessageTemplate);
columns.Bound(p => p.Level).Title(WebResources.LogListLevel);
columns.Bound(p => p.TimeStamp).Title(WebResources.LogListTimeStamp).Format("{0:dd.MM.yyyy H:mm}");
columns.Bound(p => p.Exception).Width(50).Title(WebResources.LogListException);
columns.Bound(p => p.Properties).Width(50).Title(WebResources.LogListProperties);
columns.Bound(p => p.LogEvent).Title(WebResources.LogListLogEvent);
})
.Pageable(pageable => pageable
.Refresh(true)
.ButtonCount(5))
.HtmlAttributes(new { #class = "grd_UpcomingMilestone" })
.ToolBar(toolbar =>
{
toolbar.Template(#<text>
<div class="toolbar">
<label class="category-label" for="category">#WebResources.LogFilterMessage</label>
#(Html.Kendo().DatePicker()
.Name("datepicker")
.Value(DateTime.Today)
.Format("dd.MM.yyyy")
)
#(Html.Kendo().Button()
.Name("filterButton")
.Icon("filter")
.Content("Filter")
.HtmlAttributes(new { type = "button" })
)
</div>
</text>);
})
.DataSource(source => source
.Ajax()
.Batch(true)
.ServerOperation(false)
.PageSize(100)
.Read(read => read.Action("Grid_ReadLogAdminList", "LogAdmin").Data("getFilterDate"))
))
I don't know what to do exactly in the javascript. the code works fine in the first request but not when I filter.
what should I write as a javascript?
thank you very much.
You have to pass data from client to server using getFilterDate function specified in you Kendo Grid Read Data method. Implement a function like this. The return type must be an object with fields with the same name you defined in your MVC Action, in this case date. Kendo will serialize them in order to build the get request:
function getFilterDate() {
var mydate = $("#datepicker").data("kendoDatePicker").value();
return {
"date": mydate
}
}
I have a grid on Kendo UI that has GROUP, however an error occurs when I ask you to clean the grid data via JavaScript, follow the grid code Razor:
#(Html.Kendo().Grid<ItemViewModel>(Model.FormasPagamento)
.Name("grid")
.Columns(clm =>
{
clm.Group(g => g.Title("FormaPagamento")
.Columns(subitem =>
{
subitem.Bound(e => e.Dias)
.Title("Dias").Width(60).ClientTemplate("#=kendo.format('{0:n0}', Dias)#");
subitem.Bound(e => e.Percentual)
.Title("Percentual").Width(100).ClientTemplate("#=kendo.format('{0:p}', Percentual / 100)#");
subitem.Bound(e => e.Valor)
.Title("Valor").Width(100).ClientTemplate("#=kendo.format('{0:n2}', Valor)#");
})
);
clm.Group(g => g.Title("Parcela")
.Columns(subitem =>
{
subitem.Bound(e => e.ParcelaValor)
.Title("Valor").Width(100).ClientTemplate("#=kendo.format('{0:n2}', ParcelaValor)#");
subitem.Bound(e => e.ParcelaTaxa)
.Title("Taxa").Width(100).ClientTemplate("#=kendo.format('{0:n2}', ParcelaTaxa)#");
subitem.Bound(e => e.ParcelaContratoCambio)
.Title("ContratoCambio").Width(200);
subitem.Bound(e => e.ParcelaStatus)
.Title("Status").Width(80);
})
);
})
.ToolBar(t =>
{
t.Template("<span class=\"adicionarItemGridFormaPagamento k-button k-button-icontext\"><span></span>Adicionar</span>");
})
.Navigatable()
.Editable(a =>
{
a.Mode(GridEditMode.InCell);
a.DisplayDeleteConfirmation("Excluir?");
})
.Scrollable(s => s.Height("auto"))
.Selectable(s => s.Mode(GridSelectionMode.Single))
.Filterable()
.ColumnMenu()
.Sortable()
.Pageable()
.DataSource(da => da
.Ajax()
.Batch(true)
.PageSize(1000)
.Events(e => e.Error("onErrorGrid"))
.Destroy("", "", Model)
.Create("", "", Model)
.Update("", "", Model)
.Model(m =>
{
m.Id(p => p.ItemId);
m.Field(p => p.ParcelaValor).Editable(false);
m.Field(p => p.ParcelaStatus).Editable(false);
m.Field(p => p.ParcelaTaxa).Editable(false);
m.Field(p => p.ParcelaContratoCambio).Editable(false);
}))
)
Follows the JavaScript command to clear the grid data, when it reaches this point the browser code enters into an infinite loop and lock the application:
<script>
var grid = $("#grid").data("kendoGrid");
grid.dataSource.data([]); //ERROR
</script>
This problem does not occur with Kendo grid without GROUP, one would have any idea how to use this call without experience this bug?
I am using ASP.NET MVC5 and Kendo 2015.3.1111.545
I'm trying to display a pop up window when a user clicks on a button but I cant seem to get this to work. I can fire the event when using a custom command but I need a textbox and button next to each other in the same column.
Any ideas why this isn't working?
#(Html.Kendo().Grid(Model)
.Name("gridPopup")
.Columns(columns =>
{
columns.Bound(p => p.ProductName).Width(120);
columns.Template(#<text></text>).Title("").Width(110).ClientTemplate(
Html.Kendo().TextBox()
.Name("search_textfield")
.Value("").ToClientTemplate().ToString()
+ " " +
Html.Kendo().Button()
.Name("search_button")
.HtmlAttributes(new { type = "button", #class = "k-primary" })
.Events(e =>
e.Click("SearchButton")
)
.Content("...").ToClientTemplate().ToString()
);
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Pageable()
.Scrollable()
.HtmlAttributes(new { style = "height:320px;" })
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.PageSize(20)
.ServerOperation(false)
.Events(events => events.Error("errorHandler"))
.Model(model =>
{
model.Id(p => p.ProductID);
model.Field(p => p.ProductID).Editable(true);
model.Field(p => p.CategoryID).DefaultValue(1);
})
.Read(read => read.Action("ForeignKeyColumn_Read", "Home"))
.Update(update => update.Action("ForeignKeyColumn_Update", "Home"))
.Create(create => create.Action("ForeignKeyColumn_Create", "Home"))
.Destroy(destroy => destroy.Action("ForeignKeyColumn_Destroy", "Home"))
)
)
<script type="text/javascript">
function errorHandler(e) {
if (e.errors) {
var message = "Errors:\n";
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function () {
message += this + "\n";
});
}
});
alert(message);
}
}
function SearchButton(e)
{
alert("Search Button Clicked");
}
</script>
Weird! .Events(e => e.Click("SearchButton")) is not generating the onclick attribute if used inside a ClientTemplate()
Try this, it will work for you, but i will wait for someone to explain it :)
.HtmlAttributes(new { type = "button", #class = "k-primary", onclick = "SearchButton()" })
Edit:
The explanation that I found is here: How do I use a Kendo UI widget inside a Grid client column template?. It says script tags are not automatically evaluated inside a Grid client column template, so any included widgets will not be initialized.
Therefore initializing the nested controls in .Events(e => e.DataBound("onDatabound"))
function onDatabound()
{
jQuery("#gridPopup tbody [class='k-primary']").each(function () {
$(this).kendoButton({ "click": SearchButton });
})
}
I'm using a Kendo UI Web Grid in an ASP.Net MVC 4 application.
At the bottom of the code below you'll see a JavaScript function called GetEditChildUrl that accepts a parameter called data. Unfortunately, what gets passed in as the data parameter is the parent row data but I was expecting the child row data. This works fine for GetEditParentUrl. So how do I get the child row data?
#(Html.Kendo().Grid<Application.Models.Parent>()
.Name("grid_parent")
.Columns(columns =>
{
columns.Bound(x => x.Name);
columns.Bound(x => x).ClientTemplate(
"<a href='#= GetEditParentUrl(data) #' class='k-button' style='min-width:0px;'><span class='k-icon k-i-pencil'></span></a>"
).Width(90).Filterable(false);
})
.Scrollable(action => action.Virtual(true))
.Filterable()
.Sortable()
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Parents_Read", "Parent"))
)
.Scrollable(s => s.Height("auto"))
.ClientDetailTemplateId("client-template")
)
#section Scripts {
<script id="client-template" type="text/x-kendo-template">
<h3>Contacts</h3>
#(Html.Kendo().Grid<Application.Models.Child>()
.Name("grid_child_#=Id#") // make sure the Name is unique
.Columns(columns =>
{
columns.Bound(x => x.Name);
columns.Bound(x => x).ClientTemplate(
"<a href='#= GetEditChildUrl(data) #' class='k-button' style='min-width:0px;'><span class='k-icon k-i-pencil'></span></a>"
).Width(90).Filterable(false);
})
.DataSource(dataSource =>
dataSource.Ajax().Read(read => read.Action("Children_Read", "Parent", new { parentId = "#=Id#" }))
)
.Scrollable(s => s.Height("auto"))
.Sortable()
.ToClientTemplate()
)
</script>
<script>
function GetEditParentUrl(data) {
return "#Url.Action("Edit", "Parent")/" + data.Id;
}
function GetEditChildUrl(data) {
return "#Url.Action("Edit", "Child")/" + data.Id;
}
</script>
}
Try escaping the hash (#) symbols in your column client template.
columns.Bound(x => x)
.ClientTemplate("<a href='\\#= GetEditChildUrl(data) \\#' ...>")
From the KendoUI docs:
Important: The "#" characters used for a template expression should be
escaped when using a column ClientTemplate in a detail template so
that the expression is evaluated in the correct context.