how to get selected row value in the KendoUI - grid

I have a kendoUI grid.
#(Html.Kendo().Grid<EntityVM>()
.Name("EntitesGrid")
.HtmlAttributes(new { style = "height:750px;width:100%;scrollbar-face-color: #eff7fc;" })
.Columns(columns =>
{
columns.Bound(e => e.Id).Hidden().IncludeInMenu(false);
columns.Bound(e => e.EntityVersionId).Hidden().IncludeInMenu(false);
columns.Bound(e => e.Name).Width("70%").Title("Entity Name");
columns.Bound(e => e.EIN).Width("30%");
})
.ToolBar(toolBar => toolBar.Template("<a class='k-button k-button-icontext k-grid-add' id='addEntity'><span class='k-icon k-add'></span>Entity</a>" +
"<a class='k-button k-button-icontext' id='editEntity'><span class='k-icon k-edit'></span>Edit</a>"))
.DataSource(dataSource => dataSource
.Ajax().ServerOperation(false)
.Model(model => model.Id(e => e.Id))
.Read(read => read.Action("GetEntities", "Entity", new { projectId = Request.QueryString[DataKeyNameConstants.ProjectId] })))
.Sortable()
.Scrollable()
.Filterable()
.Resizable(resize => resize.Columns(true))
.Reorderable(reorder => reorder.Columns(true))
.ColumnMenu()
.Selectable(s => s.Mode(GridSelectionMode.Multiple))
.Events(events => events.Change("entSelChange"))
)
now, I need to get the value of EntityVersionId from the selected Row. but not sure how to do it.
here's my javascript function
$("#editEntity").click(function () {
var entityGrid = $("#EntitesGrid").data("kendoGrid");
// what should I do from here
});
UPDATE: add code to loop all rows.
function loadPreviousEntityVersion() {
alert("sdfsdfsdf");
var entityGrid = $("#EntitesGrid").data("kendoGrid");
var data = entityGrid.dataSource.data();
for(var i = 0; i<data.length; i++) {
var currentDataItem = data[i];
alert(dataItem.EntityVersionId);
}
}

One way is to use the Grid's select() and dataItem() methods.
In single selection case, select() will return a single row which can be passed to dataItem()
var entityGrid = $("#EntitesGrid").data("kendoGrid");
var selectedItem = entityGrid.dataItem(entityGrid.select());
// selectedItem has EntityVersionId and the rest of your model
For multiple row selection select() will return an array of rows. You can then iterate through the array and the individual rows can be passed into the grid's dataItem().
var entityGrid = $("#EntitesGrid").data("kendoGrid");
var rows = entityGrid.select();
rows.each(function(index, row) {
var selectedItem = entityGrid.dataItem(row);
// selectedItem has EntityVersionId and the rest of your model
});

There is better way. I'm using it in pages where I'm using kendo angularJS directives and grids has'nt IDs...
change: function (e) {
var selectedDataItem = e != null ? e.sender.dataItem(e.sender.select()) : null;
}

I think it needs to be checked if any row is selected or not?
The below code would check it:
var entityGrid = $("#EntitesGrid").data("kendoGrid");
var selectedItem = entityGrid.dataItem(entityGrid.select());
if (selectedItem != undefined)
alert("The Row Is SELECTED");
else
alert("NO Row Is SELECTED")

If you want to select particular element use below code
var gridRowData = $("<your grid name>").data("kendoGrid");
var selectedItem = gridRowData.dataItem(gridRowData.select());
var quote = selectedItem["<column name>"];

Related

GetItemLinqQueryable doesn't return any items

I have two sets of code (below) that fetches items from a container that match conditions specified in "where" statement. One with the sql query works as expected whereas the other with the Linq expressions doesn't. The Linq one would return items if I remove all "Where" statements but what I want is to fetch items matching the conditions in those "Where" statements. Can you help me understand why the Linq one doesn't work?
QueryRequestOptions queryRequestOptions = new QueryRequestOptions()
{
MaxItemCount = DefaultPageSize, // 100
};
// THIS CODE WORKS
string query = $"SELECT * FROM root r WHERE r.documentType = #documentType and r._ts > #timestamp";
QueryDefinition queryDefinition = new QueryDefinition(query);
queryDefinition.WithParameter("#documentType", docType);
queryDefinition.WithParameter("#timestamp", TimestampConverter.ToTimestamp(fromTime));
using (var feedIterator = container.GetItemQueryIterator<T>(
queryDefinition,
null,
queryRequestOptions))
{
while (feedIterator.HasMoreResults)
{
FeedResponse<T> feedResponse = await feedIterator.ReadNextAsync(cancellationToken);
// THIS CODE DOESN"T WORK
using (var feedIterator = container.GetItemLinqQueryable<T>(false, null, queryRequestOptions)
.Where(d => d.DocumentType == docType)
.Where(d => d.Timestamp > fromTime)
.ToFeedIterator())
{
while (feedIterator.HasMoreResults)
{
FeedResponse<T> feedResponse = await feedIterator.ReadNextAsync(cancellationToken);
}
you can try like this
select many is used wherever i have an array in document
container.GetItemLinqQueryable<>()
.Where(ar => ar.FiscalYear == fiscalYear)
.SelectMany(ar => ar.ResourcePrivileges.Where(arp => arp.ResourceName == accessRequest.PendingUserRequest.ResourcePrivileges.ResourceName)
.SelectMany(rp => rp.Filters.Where(f => (int)f.Role > 2 && subRegionLst.Contains(f.SubRegion) && reqProduct.Contains(f.ProductName)))
.Select(i => new
{
Alias = ar.UserAlias,
Filter = ar.ResourcePrivileges.Where(arp => arp.ResourceName == accessRequest.PendingUserRequest.ResourcePrivileges.ResourceName).SelectMany(x => x.Filters),
})).Distinct();
I believe your issue has to do with how the linq query in serialized. By default GetItemLinqQueryable doesn't use camel case.
You can control the serialization by passing serializing options:
container.GetItemLinqQueryable<T>(
linqSerializerOptions: new CosmosLinqSerializerOptions
{
PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase
});

Kendo grid edit template data bind - no data

I have a problem with edit template data bind for kendo grid.
I have binded my grid to model which is DataTable(it must be DataTable because all cloumns must be generated dynamic - I do not know the schema), I added export, sortable, pages etc. I also added edit button, and defined another cshtml file with edit template. It all works almost perfect. One problem is that I receive the empty model for edit template.
View:
#(Html.Kendo().Grid(Model.Data)
.Name("OpertionalViewGrid")
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(false)
.Events(events => events.Error("error_handler"))
.Model(model =>
{
model.Id(p => p.Row[0]);
if (Model.Data != null)
{
foreach (System.Data.DataColumn column in Model.Data.Columns)
{
var field = model.Field(column.ColumnName, column.DataType);
}
}
})
.PageSize(20)
.Read(read =>
read.Action("Export_Read","OperationalView").Data("getRow"))
.Update(up => up.Action("UpdateRow", "OperationalView").Data("getRow"))
)
.Columns(c =>
{
if (Model.Data != null)
{
int index = 0;
foreach (System.Data.DataColumn column in Model.Data.Columns)
{
var col = c.Bound(column.ColumnName).Width("300px");
if (index < 2)
{
col.Locked(true).Lockable(false);
}
index++;
}
c.Command(command => { command.Edit();}).Width(100);
}
})
.Editable(editable => editable
.Mode(GridEditMode.PopUp)
.TemplateName("OperationalViewEditor")
)
.Scrollable()
.Reorderable(reorder => reorder.Columns(true))
.Resizable(r => r.Columns(true))
.Filterable(ftb => ftb.Mode(GridFilterMode.Row))
.HtmlAttributes(new { style = "height:100%" })
.Pageable()
.Navigatable()
.Sortable()
.Groupable(g => g.ShowFooter(true))
.ToolBar(tools => tools.Excel())
.Excel(excel => excel.AllPages(true))
.ToolBar(tools => tools.Pdf())
.Pdf(pdf => pdf
.AllPages()
.AvoidLinks()
.PaperSize("A4")
.Scale(0.8)
.Margin("2cm", "1cm", "1cm", "1cm")
.Landscape()
.RepeatHeaders()
.TemplateId("page-template")
.FileName("Export.pdf")
)
)
I have also my getRow function:
<scriprt>
function getRow()
{
var grid = $('#OpertionalViewGrid').data('kendoGrid');
var selectedItem = grid.dataItem(grid.select());
return selectedItem;
} </script>
In my controler I have:
public ActionResult Export_Read([DataSourceRequest]DataSourceRequest request)
{
var ovs = new OperationalViewService();
return Json(ovs.Read()/*.ToDataSourceResult(request)*/);
}
public ActionResult UpdateRow([DataSourceRequest] DataSourceRequest dsRequest, DataRowView row)
{
var t = 5;
return Json(row/*ModelState.ToDataSourceResult()*/);
}
And my edit template:
#model System.Data.DataRowView
<h3>Customized edit template</h3>
#if(Model == null)
{
<label> null</label>
}
else
{
<label> not null!!!!!!</label><br />
#Html.Label(Model.DataView.Table.Columns.Count.ToString())<br />
#Html.Label(Model.ToString())<br />
#Html.Label(Model.Row.Table.Columns.Count.ToString())<br />
}
#for (int i = 0; i < Model.DataView.Table.Columns.Count; i++)
{
#Html.LabelFor(model => model.DataView.Table.Columns[i].ColumnName.ToString())
#Html.LabelFor(model => model.Row[i].ToString())
<br />
}
So.. when I click Edit button, I get a window with proper header, with note "01234 not null!! 0 DataRowView 0 "
So I conclude that model is of proper type, one problem is to pass my selected row.
I am very new to web and Kendo/telerik so my question: how to send my selected grid row to edit template?
Another question is: why when I click "edit" i do not get into UpdateRow action in my controler?
I have ommited the problem by using edit mode InCell - one important note is to specify the column type, as shown here: http://www.telerik.com/forums/inline-batch-crud-fails-with-datatable-model

Chain HTTP calls

I have a REST API that returns an array of appointments. For each item in this array I want to make an single call against another API to get more Information for the item.
this.httpClient.get(this.serverUrl, this.httpOptions.RequestOptions)
.map(res => res.json())
.map((items: Array<any>) => {
let list: Array<MettAppointmentModel> = [];
if (items) {
items.forEach(item => {
let model = new MettAppointmentModel();
model.Created = item.created;
model.CreatedBy = item.createdBy;
model.Date = item.date;
model.Id = item._id;
model.participated = this.httpClient.get(this.serverUrl + model.Id, this.httpOptions).map(response => return response.json());
list.push(model);
});
}
return list;
} );
I don't know how to get another call chained in this call
model.participated = this.httpClient.get(this.serverUrl + model.Id, this.httpOptions).map(response => return response.json());

Reference members in Moq lambda

I have a function in a class that returns a value based on the state of a class property. In this example, I want HasName() to return true if Name is not null. I could simply do Returns(false), however I want it evaluate as a lambda so that it works properly if Name is modified during the test.
public interface IThing
{
string Name { get; set; }
bool HasName();
}
var mocks = new Dictionary<string, IThing>();
Mock<IThing> mockThing;
mockThing = new Mock<IThing>();
mockThing.SetupProperty(m => m.Name, "test");
mockThing.Setup(m => m.HasName()).Returns(() =>
{
return mockThing.Object.Name != null;
});
mocks["first"] = mockThing.Object;
mockThing = new Mock<IThing>();
mockThing.SetupProperty(m => m.Name, "test");
mockThing.Setup(m => m.HasName()).Returns(() =>
{
return mockThing.Object.Name != null;
});
mocks["second"] = mockThing.Object;
Console.WriteLine(mocks["first"].HasName());
mocks["first"].Name = null;
Console.WriteLine(mocks["first"].HasName());
The 2nd Console.WriteLine prints true instead of false due to scoping (referencing the 2nd mock). Resharper actually complains of "Access to modified closure". What is the correct way to do this?
Although your design a little bit strange but you can access the generated mock object with mockThing.Object in your Setup function:
mockThing.Setup(m => m.HasName()).Returns(() =>
{
return mockThing.Object.Name != null;
});
var thing = mockThing.Object;
var hasName = thing.HasName(); // true because Name returns "test"
thing.Name = null;
hasName = thing.HasName(); // false
The problem is that you are referencing the mockThing with your lambdas and then you are reasigning it. So both setup will end up using the same instance.
Use the mocks from the dictionary and it will work:
var mocks = new Dictionary<string, IThing>();
Mock<IThing> mockThing;
mockThing = new Mock<IThing>();
mocks["first"] = mockThing.Object;
mockThing.SetupProperty(m => m.Name, "test");
mockThing.Setup(m => m.HasName()).Returns(() =>
{
return mocks["first"].Name != null;
});
mockThing = new Mock<IThing>();
mocks["second"] = mockThing.Object;
mockThing.SetupProperty(m => m.Name, "test");
mockThing.Setup(m => m.HasName()).Returns(() =>
{
return mocks["second"].Name != null;
});
Console.WriteLine(mocks["first"].HasName());
mocks["first"].Name = null;
Console.WriteLine(mocks["first"].HasName());

How to display enum description or name in a grid row?

I am using the Kendo grid in my ASP.Net MVC application. If I have the following grid definition,
#(Html.Kendo().Grid(Model) //Bind the grid to ViewBag.Products
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.FullName);
columns.Bound(p => p.MyEnum)
})
.Groupable()
.Pageable()
.Sortable()
.Scrollable(scr => scr.Height(600))
.Filterable()
)
where one of the column is an Enum. My enum definition is:
public enum MyEnum
{
[Display(AutoGenerateField = false, Name = "My enum 1", Description = "My Enum 1")]
EnumOne,
[Display(Name = "My Enum 2")]
EnumTwo
}
How do I make it display "My Enum 1" or "My Enum 2" for each row?
Thanks in advance!
I recently ran into this problem and solved it by using
var someArrayOfValueAndText = new[] {new {
Id = 0, Description = "Foo"
}, new {
Id = 1, Description = "Bar"
}
.Columns(c.ForeignKey(m=> m.MyEnum, someArrayOfValueAndText, "Id","Description"))
instead of the .Bound method
I created an helper class containing some extension methods a while back:
public static class EnumExtensions
{
public static string GetDisplayName(this Enum enu)
{
var attr = GetDisplayAttribute(enu);
return attr != null ? attr.Name : enu.ToString();
}
public static string GetDescription(this Enum enu)
{
var attr = GetDisplayAttribute(enu);
return attr != null ? attr.Description : enu.ToString();
}
private static DisplayAttribute GetDisplayAttribute(object value)
{
Type type = value.GetType();
if (!type.IsEnum)
{
throw new ArgumentException(string.Format("Type {0} is not an enum", type));
}
// Get the enum field.
var field = type.GetField(value.ToString());
return field == null ? null : field.GetCustomAttribute<DisplayAttribute>();
}
}
It contains two methods for extracting the Name and Description of a Display attribute. The display name:
columns.Bound(p => p.MyEnum.GetDisplayName())
And for a description:
columns.Bound(p => p.MyEnum.GetDescription())
You have to add a using statement in your Web.config or in your view.
Update
What if you create a property for it in your model:
public string MyEnumName
{
get { return MyEnum.GetDisplayName(); }
}
Now you should be able to use:
columns.Bound(p => p.MyEnumName);
Henk's solution is good. But you can use filtering capability if you use ClientTemplate:
col.Bound(m => m.MyEnum) // this provides you filtering
.ClientTemplate("#: MyEnumName #") // this shows a name of enum
For more information about kendo ui templates see: http://docs.telerik.com/kendo-ui/framework/templates/overview
I use #user1967246 method and would like to explain more how to i do.
i created array in top of my kendo grid
var statusLikeEntityStatus = new[]
{
new {Id = 0, Status = EntityStatus.Passive},
new {Id = 1, Status = EntityStatus.Active},
new {Id = 2, Status = EntityStatus.Draft},
new {Id = 3, Status = EntityStatus.ReadyToLive},
new {Id = -1, Status = EntityStatus.Freezed},
new {Id = -2, Status = EntityStatus.Blocked}
};
Then i use ForeignKey property instead of Bound.
columns.ForeignKey(m => m.Status, statusLikeEntityStatus, "Id", "Status").Title(Resources.General.Status);
Here is my columns attribute
.Columns(columns =>
{
columns.Bound(m => m.InventoryID).Title("Id");
columns.Bound(m => m.ERPCode).Title(Resources.Products.ProductCode);
columns.Bound(m => m.Price).Title(Resources.Products.ListPrice);
columns.Bound(m => m.Discount).Title(Resources.Products.
columns.Bound(m => m.Stock).Title(Resources.Products.TotalStock); // todo: Resources
columns.ForeignKey(m => m.Status, statusLikeEntityStatus, "Id", "Status").Title(Resources.General.Status);
columns.Command(commandConf =>
{
commandConf.Edit();
commandConf.Destroy();
});
})
Hope it will help to you.

Resources