kendo grid filter operator - javascript

I have a datasource I use for a grid.
The grid has server filtering, which works fine.
The issue is-Filter is giving the results based on contains operator only(irrespective of what I have selected)
how to get the filter operator from filter operator options.
Please help me
#(Html.Kendo().Grid(Model).Name("ViewDataGrid")
.Columns(columns =>
{
columns.Bound(c => c.Id).Title(" ID").Width(150);
columns.Bound(c => c.Name).Title(" Name").Width(150);
})
.HtmlAttributes(new { style = "height: auto; width: 2200px" })
.Filterable(i => i.Mode(GridFilterMode.Menu | GridFilterMode.Row))
.Sortable(s => s.AllowUnsort(false).SortMode(GridSortMode.MultipleColumn))
.Selectable(selecting => selecting.Enabled(true))
.Pageable(r => r.PreviousNext(true).PageSizes(new int[] { 10, 20, 30, 40, 50, 100 }))
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.ServerOperation(false)
.Events(e => e.Change("call"))
))
function call(e) {
if (e.sender.filter.arguments[0].filters != null) {
if (e.sender.filter.arguments[0].filters[0].value == "") {
$('#ViewDataGrid').data('kendoGrid').dataSource.filter({});
}
else {
var filterlength = e.sender.filter.arguments[0].filters.length;
$filter = new Array();
if (e.sender.filter.arguments[0].filters[0].field == "Id")
$filter.push({ field: e.sender.filter.arguments[0].filters[0].field, operator: "eq", value: e.sender.filter.arguments[0].filters[0].value });
else
$filter.push({ field: e.sender.filter.arguments[0].filters[0].field, operator: "contains", value: e.sender.filter.arguments[0].filters[0].value });
$("#ViewDataGrid").data("kendoGrid").dataSource.filter($filter);
}
}
}
Model.CS
public int Id { get; set; }
public string Name { get; set; }
Controller
public ActionResult Index()
{
List<GridData> dataList = new List<GridData>();
GridData data1 = new GridData();
data1.Id = 9191919;
data1.Name = "XYZ";
dataList.Add(data1);
return View(dataList);
}

you might enable only the 'Is equal to' filter for the ID field
#(Html.Kendo().Grid(Model).Name("ViewDataGrid")
.Columns(columns =>
{
columns.Bound(c => c.Id).Title(" ID").Width(150).Filterable(f => f.Operators(op => op.ForNumber(opn => opn.Clear().IsEqualTo("Is equal to") )));
columns.Bound(c => c.Name).Title(" Name").Width(150);
})
.HtmlAttributes(new { style = "height: auto; width: 300px" })
.Filterable(i => i.Mode(GridFilterMode.Menu | GridFilterMode.Row))
.Sortable(s => s.AllowUnsort(false).SortMode(GridSortMode.MultipleColumn))
.Selectable(selecting => selecting.Enabled(true))
.Pageable(r => r.PreviousNext(true).PageSizes(new int[] { 10, 20, 30, 40, 50, 100 }))
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.ServerOperation(false)
))

Related

ASP.NET MVC Kendo Grid how to call controller method from javascript

Because I have a custom modal confirmation popup, I'll need to call the the method .Destroy("Remove", "Attachment") from javascript. How do I call the Remove method from javascript? I've indicated in the code how to call where I'd like to be able to call the method. Also, how to pass through the OrderViewModel?
Here's my grid:
#(Html.Kendo().Grid<TelerikAspNetCoreApp7.Models.OrderViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.OrderID).Filterable(false);
columns.Bound(p => p.Freight);
columns.Bound(p => p.OrderDate).Format("{0:MM/dd/yyyy}");
columns.Bound(p => p.ShipName);
columns.Bound(p => p.ShipCity);
columns.Command(command =>
{
command.Custom("Destroy")
.Click("showDeleteConfirmation")
.HtmlAttributes(new { style = "width:40%" });
}).Width("15%");
})
.Pageable()
.Sortable()
.Scrollable()
.Filterable()
.HtmlAttributes(new { style = "height:550px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Destroy("Remove", "Attachment")
.Read(read => read.Action("Orders_Read", "Grid"))
.Destroy(read => read.Action("Orders_Read", "Grid"))
)
)
The modal:
#(Html.Kendo()
.Dialog()
.Name("DeleteConfirmation")
.Modal(true)
.Title("Confirm Delete")
.Content("Are you sure you want to delete this item?")
.Visible(false)
.Actions(a =>
{
a.Add().Text("No").Action("cancelDelete");
a.Add().Text("Yes").Action("confirmDelete").Primary(true);
})
)
The scripts:
<script>
var modelToDelete;
function showDeleteConfirmation(e) {
e.preventDefault();
var grid = $("#grid").data("kendoGrid");
var dialog = $('#DeleteConfirmation').data("kendoDialog");
modelToDelete = grid.dataItem($(e.target).parents('tr'));
dialog.content("Are you sure you want to delete this item with ID - " + modelToDelete.OrderID + "?");
dialog.open();
}
function confirmDelete(e) {
//how to call .Destroy("Remove", "Attachment") from here
}
function cancelDelete() {
}
</script>
The controller:
public ActionResult Remove([DataSourceRequest] DataSourceRequest request, OrderViewModel attachmentVm)
{
Attachment attachment = _db.Attachments.FirstOrDefault(o => o.Guid == attachmentVm.Guid);
attachment.IsActive = false;
attachment.LastUpdated = DateTime.Now;
attachment.LastUpdatedBy = _sessionUser.Username;
_db.SaveChanges();
return Json(ModelState.ToDataSourceResult());
}
Here's the answer:
function confirmDeleteAttach(e) {
$.ajax({
url: '/Attachment/Remove',
data: { Guid: modelToDeleteAttach.Guid },
type: "POST",
success: function () {
gridToDeleteAttach.dataSource.remove(modelToDeleteAttach);
$('#DeleteConfirmationAttach').data("kendoDialog").close();
}
});
}

Why when reloading Kendo UI GRID page from browser url, all of data do not display and just display grid without data?

when i reload the kendo grid page,the Information is lost and you have to stop the program and restart it!? where is my problem and how to fix it?
this is my view of kendo ui grid in ASP.NET MVC 5:
#using Microsoft.AspNet.Identity.EntityFramework;
#using UserManagerSample.ViewModels;
#using Kendo.Mvc.UI
<script
src="http://cdn.kendostatic.com/2013.3.1119/js/kendo.aspnetmvc.min.js">
#(Html.Kendo(). Grid<UserViewModel>() .Name("grid")
.Columns(columns =>
{
columns.Bound(p =>
p.UserName);
columns.Bound(p => p.password);
columns.Bound(p => p.ConfirmPassword);
columns.Bound(p =>
p.Fakerole).ClientTemplate("#=Fakerole.FakeRoleName#")
.Title("Role").EditorTemp
lateName("FakeRoleDropDownList").Width(180);
columns.Command(command => command.Destroy()).Width(150);
})
.ToolBar(toolBar =>
{
toolBar.Create();
toolBar.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.ClientDetailTemplateId("Test")
.Pageable()
.Sortable()
.Scrollable()
.HtmlAttributes(new { style = "height:550px;" })
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(false)
.Events(events => events.Error("error_handler"))
.Model(model =>
{
model.Id(p => p.UserId);
model.Field(p => p.UserId).Editable(false);
model.Field(e => e.password);
model.Field(e => e.ConfirmPassword);
model.Field(p => p.Fakerole).DefaultValue(
ViewData["defaultCategory"] as FakeRoleViewModel);
})
.PageSize(20)
.Read(read => read.Action("EditingCustom_Read", "MyUser"))
.Create(create => create.Action("EditingCustom_Create", "MyUser"))
.Update(update => update.Action("EditingCustom_Update", "MyUser"))
.Destroy(destroy => destroy.Action("EditingCustom_Destroy", "MyUser"))
)
)
<script type="text/javascript">
function error_handler(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);
}
}
</script>
<script>
OrderDetails_Error = function (args) {
if (args.errors) {
var grid = $("#orderDetailsGrid").data("kendoGrid");
var validationTemplate =
kendo.template($("#orderDetailsValidationMessageTemplate").html());
grid.one("dataBinding", function (e) {
e.preventDefault();
$.each(args.errors, function (propertyName) {
// take the template and insert it into the placeholder
var renderedTemplate = validationTemplate({ field:
propertyName, messages: this.errors });
grid.editable.element.find(".errors").append(renderedTemplate);
});
});
}
};
</script>
<script type="text/x-kendo-template"
id="orderDetailsValidationMessageTemplate">
# if (messages.length) { #
<li>#=field#
<ul>
# for (var i = 0; i < messages.length; ++i) { #
<li>#= messages[i] #</li>
# } #
</ul>
</li>
# } #
</script>
<script>
function dataBound() {
this.expandRow(this.tbody.find("tr.k-master-row").first());
}
</script>
It show all of the data for the first time, but when reload the the information, do not show data in grid!

Kendo mvc grid with multiselect column. Row is null reference

I have two models with relationship "Many to Many", Books, Authors, and their context Library. All source files included correctly. Cannot set selected Authors to the cell(because row is null, so model cannot be set). There is using InCell editor. I will be glad to any ideas)
UPD: new error occurred when I add a new line
Unable to get property 'map' of undefined or null reference
Index.cs.html:(error in change function, second error in dataBound function)
#{
ViewBag.Title = "Home Page";
}
#(Html.Kendo().Grid<ManyToMany.Models.ViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(e => e.BookId).Visible(false);
columns.Bound(e => e.Pages);
columns.Bound(e => e.Genre);
columns.Bound(e => e.Publisher);
columns.Bound(e => e.Authors).ClientTemplate(
Html.Kendo().MultiSelect().Name("multi#=BookId#")
.DataTextField("AuthorName")
.DataValueField("AuthorId")
.BindTo((IEnumerable<ManyToMany.Models.Author>)ViewData["authors"]) /*TaskSecond.Models.ViewModel*/
.Events(e => e.Change("change"))
.ToClientTemplate().ToHtmlString()
);
columns.Command(command => command.Destroy()).Width(150);
})
.ToolBar(toolbar =>
{
toolbar.Create();
toolbar.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Pageable()
.Filterable()
.Events(e => e.DataBound("dataBound"))
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.Model(model =>
{
model.Id(p => p.BookId);
model.Field(p => p.Pages).DefaultValue(0);
model.Field(p => p.Genre).DefaultValue(0);
model.Field(p => p.Publisher).DefaultValue("");
model.Field(p => p.Authors).DefaultValue(
ViewData["defaultAuthors"] as ManyToMany.Models.Author);
})
.PageSize(5)
.Read(read => read.Action("Books_Read", "Grid"))
.Create(create => create.Action("Books_Create", "Grid"))
.Update(update => update.Action("Books_Update", "Grid"))
.Destroy(destroy => destroy.Action("Books_Destroy", "Grid"))
.ServerOperation(false))
)
<script type="text/javascript">
function dataBound(e) {
var grid = this;
grid.tbody.children().each(function () {
var dataitem = grid.dataItem(this),
row = $(this);
eval(row.find("script").html());
var multiSelect = $(this).find("select").data("kendoMultiSelect");
//here
multiSelect.value(dataitem.Authors.map(function (i) { return i.AuthorId }));
});
}
function change(e) {
//error is here
var row = this.element.closest("tr"),
model = $("#grid").data("kendoGrid").dataItem(row);
model.set("Authors", this.dataItems());
}
</script>
ViewModel.cs:
public class ViewModel
{
public ViewModel()
{
Authors = new List<Author>();
}
public int BookId { get; set; }
public string BookName { get; set; }
public int Pages { get; set; }
public Genre Genre { get; set; }
public string Publisher { get; set; }
[UIHint("AuthorsEditor")]
public List<Author> Authors { get; set; }
}
Try using - this.select() instead of this.element.closest in the change() javascript function. You may need to refine the below code to suit your requirements, but it would give you idea of what to change when you debug through:
var row = this.select();
if (row.length > 0 )
{
selectedRow = e.sender.select();
var item = e.sender.dataItem(selectedRow);
}

Kendo grid filtering on integer column when typing

I have a grid with multiple columns.
say Id(integer),Name(string) etc.
Change event is working fine for name column.But for ID column it is not working.
I want this functionality to be in server side(Razor).
I am new to Kendo UI and any help on how to do this would be much appreciated.
I am attaching my code below:
#(Html.Kendo().Grid(Model).Name("ViewDataGrid")
.Columns(columns =>
{
columns.Bound(c => c.Id).Title(" ID").Width(150);
columns.Bound(c => c.Name).Title(" Name").Width(150);
})
.HtmlAttributes(new { style = "height: auto; width: 2200px" })
.Filterable(i => i.Mode(GridFilterMode.Menu | GridFilterMode.Row))
.Sortable(s => s.AllowUnsort(false).SortMode(GridSortMode.MultipleColumn))
.Selectable(selecting => selecting.Enabled(true))
.Pageable(r => r.PreviousNext(true).PageSizes(new int[] { 10, 20, 30, 40, 50, 100 }))
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.ServerOperation(false)
.Events(e => e.Change("call"))
))
function call(e) {
if (e.sender.filter.arguments[0].filters != null) {
if (e.sender.filter.arguments[0].filters[0].value == "") {
$('#ViewDataGrid').data('kendoGrid').dataSource.filter({});
}
else {
var filterlength = e.sender.filter.arguments[0].filters.length;
$filter = new Array();
if (e.sender.filter.arguments[0].filters[0].field == "Id")
$filter.push({ field: e.sender.filter.arguments[0].filters[0].field, operator: "eq", value: e.sender.filter.arguments[0].filters[0].value });
else
$filter.push({ field: e.sender.filter.arguments[0].filters[0].field, operator: "contains", value: e.sender.filter.arguments[0].filters[0].value });
$("#ViewDataGrid").data("kendoGrid").dataSource.filter($filter);
}
}
}
Model.CS
public int Id { get; set; }
public string Name { get; set; }
Controller
public ActionResult Index()
{
List<GridData> dataList = new List<GridData>();
GridData data1 = new GridData();
data1.Id = 9191919;
data1.Name = "XYZ";
dataList.Add(data1);
return View(dataList);
}
Try using "row" selection type:
.Selectable(selecting => selecting.Enabled(true).Type(GridSelectionType.Row))

Kendo ui aspnet mvc grid bind json object returned from action to new row

I have autocomplete control on my grid. After selecting an element from autocomplete I call an event select "onSelectArticle" to import the object using LineBonLivraison_Add action and want to bind it as a json object and not just set values to columns.
The problem happens only to a new added row. For example, when I edit existing rows I can get the properties of the selected object and set values to it like (var item = grid.dataItem(select); item.set("Document", data.Document);) but for new a new row, "item" is null
#section LinesTab {
<style>
.k-widget .templateCell
{
overflow: visible;
}
</style>
<script>
function initMenus(e) {
$(".templateCell").each(function () {
eval($(this).children("script").last().html());
});
}
function onEditGrid(editEvent) {
// Ignore edits of existing rows.
if (!editEvent.model.isNew() && !editEvent.model.dirty) {
//alert("not new dirty")
return;
}
editEvent.container
.find("input[name=Document]") // get the input element for the field
.val("100") // set the value
.change(); // trigger change in order to notify the model binding
}
</script>
<div class="lines-tab-doc">
#(Html.Kendo().Grid<LineBonLivraison>()
.Name("grid-lines-doc")
// Declare grid column
.Columns(columns =>
{
// Cretae all the columns base on Model
columns.Bound(l => l.Article).EditorTemplateName("AutoCompleteArticle");
columns.Bound(l => l.Designation);
columns.Bound(l => l.Quantite);
columns.Bound(l => l.Unite);
columns.Bound(l => l.Commentaire);
columns.Bound(l => l.ReferenceExterne);
columns.Bound(l => l.Commentaire2);
// Edit and Delete button column
columns.Command(command =>
{
command.Edit();
command.Destroy();
}).Width(200);
})
.Events(ev => ev.DataBound("initMenus").Edit("onEditGrid"))
.DataSource(datasoure => datasoure.Ajax()
.Batch(true)
.Model(model =>
{
//model.Id(l => l.Document);
model.Id(l => l.Ligne);
})
.Read(read => read.Action("LinesBonLivraison_Read", "Achat"))
.Create(create => create.Action("LinesBonLivraison_Add", "Achat"))
.Update(update => update.Action("LinesBonLivraison_Update", "Achat"))
.Destroy(delete => delete.Action("LinesBonLivraison_Delete", "Achat"))
.PageSize(10)
)
// Add tool bar with Create button
.ToolBar(toolbar =>
{
toolbar.Create();
toolbar.Save();
})
// Set grid editable.
.Editable(editable => editable.Mode(GridEditMode.InCell).CreateAt(GridInsertRowPosition.Bottom))
.Scrollable(scr => scr.Height(327))
.Sortable()
.Selectable(sel => sel.Mode(GridSelectionMode.Single).Type(GridSelectionType.Row))
.Navigatable()
.Pageable(pageable =>
{
pageable.Refresh(true);
pageable.PageSizes(true);
pageable.Messages(msg => msg.Empty(null));
})
)
</div>
}
AutoComplete Template
<script>
function onSelectArticle(e) {
var dataItem = this.dataItem(e.item.index());
var url = '#Url.Action("LineBonLivraison_Add", "Achat")';
$.ajax({
url: url,
data: {
doc: $("#Numero").val(),
line: e.item.index(),
article: dataItem.Code
}, //parameters go here in object literal form
type: 'GET',
datatype: 'json',
success: function (data) {
if (data == null)
//document.getElementById('labelx').innerHTML = "null";
else {
var grid = $("#grid-lines-doc").data("kendoGrid");
var select = grid.select();
var item = grid.dataItem(select); //prob if it a new row item is null
item.set("Document", data.Document);
item.set("Ligne", data.Ligne);
item.set("Article", data.Article);
//grid.refresh();
}
},
error: function (req, status, error) {
//document.getElementById('labelx').innerHTML = error;
}
});
}
function onAutoComplete() {
return {
text: $("#Article").val()
};
}
<div>
#(Html.Kendo().AutoComplete()
.Name("Article")
.HtmlAttributes(new { style = "width:" + width + ";" })
.DataTextField("Code")
.Filter(FilterType.Contains)
.Enable(enable)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetArticles", "Fiche").Data("onAutoComplete");
})
.ServerFiltering(true);
})
.Events(e =>
{
e.Select("onSelectArticle");
})
)
Action
public JsonResult LineBonLivraison_Add(int? doc, int? line, string article)
{
Models.Achat.LineBonLivraison l = new Models.Achat.LineBonLivraison()
{
Document = doc,
Article = article,
//Fournisseur = doc.Nom,
Ligne = line,
StyleLigne = "Style1",
ReferenceExterne = article
};
return Json(l, JsonRequestBehavior.AllowGet);
}

Categories