CRUD operations in a grid inside a parent grid detail template - asp.net-mvc

Here's a sample code from the Kendo Grid Detail Template demo on the Telerik website (I've simplified the detail template by removing the tab-strip):
#(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.EmployeeViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(e => e.FirstName).Width(120);
columns.Bound(e => e.LastName).Width(120);
columns.Bound(e => e.Country).Width(120);
columns.Bound(e => e.City).Width(120);
columns.Bound(e => e.Title);
})
.Sortable()
.Pageable()
.Scrollable()
.ClientDetailTemplateId("template")
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(5)
.Read(read => read.Action("HierarchyBinding_Employees", "Grid"))
)
.Events(events => events.DataBound("dataBound"))
)
<script id="template" type="text/kendo-tmpl">
#(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.OrderViewModel>()
.Name("grid_#=EmployeeID#")
.Columns(columns =>
{
columns.Bound(o => o.OrderID).Title("ID").Width(56);
columns.Bound(o => o.ShipCountry).Width(110);
columns.Bound(o => o.ShipAddress);
columns.Bound(o => o.ShipName).Width(190);
})
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(5)
.Read(read => read.Action("HierarchyBinding_Orders", "Grid", new { employeeID = "#=EmployeeID#" }))
)
.Pageable()
.Sortable()
.ToClientTemplate()
)
</script>
I'd like to add a Create button to the child grid (Order grid) inside the template. The problem is that when a new Order is being added, I need to pass the EmployeeID to the controller, but the following does not work, even though it works for the Read action:
.Create(create => create.Action("AddOrder", "Grid", new { employeeID = "#=EmployeeID#" }))
How do I pass the EmployeeID to the controller when adding a new item to the grid in the detail template?

You should not set an EmployeeID value as a parameter in its create transport. Because you will do POST request here, the right way to do it is to pass the value as default value of EmployeeID of Grid model.
Your inner Grid should have configuration data source like this
.DataSource(ds=> ds.Ajax()
.PageSize(5)
.Read(read => read.Action("HierarchyBinding_Orders", "Grid", new { employeeID = "#: EmployeeID #" }))
.Create(create => create.Action("AddOrder", "Grid"))
.Model(model =>
{
model.Id(f => f.OrderID)
model.Field(f => f.EmployeeID).DefaultValue("#: EmployeeID #")
})
)
The moment you add new record to server its EmployeeID value has been set.
Note: EmployeeID will be assigned by string value because of this expression "#= #",you should have EmployeeID as string type. Or you will get razor error for incompatible type.

Related

Telerik Kendo Grid Doesn't Display Value Properly

i'm new to kendo UI and currently learning about custom editor.
My Problem is i managed to get my editor template working in edit mode and populate the data just fine, but somehow it won't save the value to the display grid
I Retreive all my data from API.
UPDATE:
i've managed to properly save the value from the custom editor template to the controller and it works just fine, but using clientTemplate won't display the correct value from what i select in the dropdown, and only show a string
DropDown Only Display A String
my setup code is like this
#( Html.Kendo().Grid<SalesOrderDetailVM>()
.Name("list-detail")
.Columns(columns =>
{
columns.Bound(c => c.Product).ClientTemplate("\\#=Product.ProductId\\#").Title("Products");
columns.Bound(c => c.Quantity);
columns.Bound(c => c.UnitPrice);
})
.Editable(GridEditMode.InCell)
.ToolBar(tool =>
{
tool.Create();
tool.Save();
}
)
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(false)
.Batch(true)
.Model(model =>
{
model.Id(p => p.ProductId);
model.Field(p => p.Product);
})
.Create(act => act.Action("DetailCell_Create","SalesOrder"))
)
)
DDLProduct.cshtml:
#model AAF.WEB.MVC.ViewModels.ProductVM
#(
Html.Kendo().DropDownListFor(m => m)
.DataValueField("ProductId")
.DataTextField("ProductName")
.OptionLabel("Select Product")
.BindTo((System.Collections.IEnumerable)ViewData["products"])
)
Edit Mode
DisplayMode / Out of Product Edit Mode
Use template method to acheive dropdown with kendo grid.
GridForeignKey.cshtml - it should placed in shared folder or EditorTemplates
#model object
#(
Html.Kendo().DropDownListFor(m => m)
.BindTo((SelectList)ViewData[ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Data"])
)
In your kendo grid please change like below
#( Html.Kendo().Grid<AAF.WEB.MVC.ViewModels.SalesOrderDetailVM>()
.Name("list-detail")
.Columns(columns =>
{
columns.Bound(c => c.Id)
columns.ForeignKey(c => c.ProductId, (System.Collections.IEnumerable)ViewData["Products"], "ProductId", "ProductName").Title("Products");
columns.Bound(c => c.Quantity);
columns.Bound(c => c.UnitPrice);
})
.Editable(GridEditMode.InCell)
.ToolBar(tool =>
{
tool.Create();
tool.Save();
}
)
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(false)
)
)
You can set the products data to view data. using this method you can save the product id.
Thanks
Okay after i frustrated for many hours, finally found the solution
the solution is to add a defaultvalue to the passed model in the grid
.Model(model =>
{
model.Id(p => p.ProductId);
model.Field(p => p.Product).DefaultValue(
ViewData["defaultProduct"] as ProductVM
);
})
and pass the data from the controller
// Function that get data from API
ViewData["products"] = products;
ViewData["defaultProduct"] = products.First();

Kendo grid delete button passing the details of the row

I have a kendo grid in which I want to form delete button to pass the details of the row to the controller (as I am using mvc). Then I will use these details to delete the row from the database.
I searched in kendo website and I found the part for the delete or destroy call but I don't know how to pass these details of the row to the controller.
#(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.ProductViewModel>()
.Name("Grid")
.Columns(columns => {
columns.Bound(p => p.ProductName);
columns.Bound(p => p.UnitPrice).Width(140);
columns.Bound(p => p.UnitsInStock).Width(140);
columns.Bound(p => p.Discontinued).Width(100);
columns.Command(command => command.Destroy()).Width(110);
})
.ToolBar(toolbar => {
toolbar.Create();
toolbar.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Pageable()
.Navigatable()
.Sortable()
.Scrollable()
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.PageSize(20)
.ServerOperation(false)
.Events(events => events.Error("error_handler"))
.Model(model => model.Id(p => p.ProductID))
.Create("Editing_Create", "Grid")
.Read("Editing_Read", "Grid")
.Update("Editing_Update", "Grid")
.Destroy("Editing_Destroy", "Grid")
)
)
My grid:
<div id="grid">
#(Html.Kendo().Grid<dynamic>()
.Name("BrowseGrid")
.Columns(columns =>
{
foreach (System.Data.DataColumn c in Model.Grid.Columns)
{
columns.Bound(c.ColumnName).EditorTemplateName("String");
}
columns.Command(command =>
{
command.Destroy();
command.Custom("").Text("editteam").HtmlAttributes(new { id = "editteam", onClick = "editRow()" });
});
})
.Scrollable()
.DataSource(dataSource => dataSource
.Ajax()
.Events(events => events.Error("error_handler"))
.Model(model =>
{
//Define the model
foreach (System.Data.DataColumn column in Model.Grid.Columns)
{
model.Field(column.ColumnName, column.DataType);
model.Id("Id");
}
})
.Read(read =>
read.Action("BrowseGrid", "Configuration")
)
.Destroy( update => update.Action("Delete", "Configuration"))
//Data("{nodeID:"+#Model.nodeID+"}"
)
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(new int[] { 10, 100, 1000, 10000, 100000, 1000000 })
.ButtonCount(10)
)
)
Please change to:
.Destroy(update => update.Action("Process_Destroy", "controller name"))
and in controller,
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Process_Destroy([DataSourceRequest] DataSourceRequest request, ProductViewModel product)
{
if (product != null)
{
//write your code for delete action;
}
return Json(ModelState.ToDataSourceResult());
}
This will work.
I am assuming you only need the id of the row to delete it, but I think you can send the full model of the selected row. I am sending both.
Like this:
.Destroy(d => d.Action("controllerMethod", "controllerName").Data("jsFunction"))
And in javascript:
function jsFunction() {
var grid = $("#BrowseGrid").data("kendoGrid");
var id = grid.dataItem(grid.select()).Id;
return {
id: id
};
}
Your controller method should receive the parameter:
public ActionResult controllerMethod(string id)

How can we maintain old data in kendo grid while binding Datasource

I have a kendo grid with datasource. Each time it is refreshing the old data with new data. But my requirement is quite different I also want display old data as well.
Another data source is in anotherKENDO GRID.
My Kendo Grid as below:
#(Html.Kendo().Grid<ABC>()
.Name("grdABC")
.HtmlAttributes(new { style = "height:450px" })
.Columns(columns =>
{
columns.Bound(d => d.ID).Hidden(true);
columns.Bound(d => d.Group).Hidden(true);
columns.Bound(d => d.Name).Title("Name").Width(350);
})
.Selectable(selectable => selectable
.Mode(GridSelectionMode.Multiple))
.Scrollable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.Sort(sort => sort.Add("Name").Ascending())
.Model(model => model.Id(p => p.ID))
.Read(read => read.Action("GetSelectedNames", "EligCriteria", new { Id = Model.ID != null ? Model.ID : (decimal?)null }).Data("getSelectedEligibilityNames"))
)
.AutoBind(false)
)
We can maintain using below code:
var grid = $("#GridID").data("kendoGrid");
grid.one("dataBinding", function(e){
e.preventDefault()
});

How to pass the model of a row from Kendo Grid to an editable template

I have a Kendo Grid which has a popup editable template,
If possible i would like to pass the model (the model of the row, or at least its Id) to the editable template
Grid
#(Html.Kendo().Grid<Client>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.Name).Width(140);
columns.Bound(c => c.Status);
columns.Bound(c => c.ProcesingStyle);
columns.Bound(c => c.ArchiveDays);
columns.Command(command =>
{
command.Edit().Text(" ");
command.Destroy().Text(" "); ;
}).Width(90);
})
.ToolBar(toolbar => toolbar.Create().Text("New"))
.Editable(editable => editable
.Mode(GridEditMode.PopUp)
.TemplateName("Client").AdditionalViewData(new { Client = Model })
.Window(w => w.Title("Site")))
.HtmlAttributes(new { style = "height: 380px;" })
.Scrollable()
.Sortable()
.Selectable()
.Resizable(resize => resize.Columns(true))
.Reorderable(reorder => reorder.Columns(true))
.Events(events => events.Change("onChange"))
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5))
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Get", "Clients"))
.Model(model => model.Id(p => p.Id))
.Create(update => update.Action("Create", "Clients"))
.Update(update => update.Action("Update", "Clients"))
.Destroy(update => update.Action("Destroy", "Clients"))
)
)
Template
#model Client
#(Html.Kendo().ComboBoxFor(m => m.Plan)
.DataTextField("Name")
.DataValueField("Id")
.Placeholder("Select Plan...")
.HtmlAttributes(new { style = "width:300px" })
.Filter(FilterType.Contains)
.MinLength(3)
.DataSource(source =>
source.Read(read =>
read.Action("GetPlans", "Plans",new {ClientId = Model.Id}))))
Everything works fine except i need to use the Id of the row/model inside the template, in particular , i need the to pass the model.Id (which is the id of the model of the row), to the action on the Combobox in the template, so i can filter the data correctly
This is the offending line in the grid,
.TemplateName("Client").AdditionalViewData(new { Client = Model })
The result is the Model inside the template is always null, im not sure how to pass the data i need to the template
Is there anyway i can do this, or should i be looking at a different approach?
The way I got around this was to put a JavaScript function in the original view as seen below:
function getClientId() {
var row = $(event.srcElement).closest("tr");
var grid = $(event.srcElement).closest("[data-role=grid]").data("kendoGrid");
var dataItem = grid.dataItem(row);
if (dataItem)
return { clientId: dataItem.Id }
else
return { clientId: null }
}
And reference it from my editor template:
.DataSource(source => source.Read(read => read.Action("GetPlans", "Plans").Data("getClientId"))))
Note : I'm pretty sure you cant run JavaScript from a EditorTemplate so it needed to be housed in the original view.
I know this is a really old question, but for those who are wondering why this doesn't work:
.TemplateName("Client").AdditionalViewData(new { Client = Model })
This code doesn't work because the only data you can pass through this method is static data. You can pass specific strings or numbers, like "Hello World", and that would work fine. For dynamic data with kendo, I've learned that it really depends on the situation, and your solution here works well.

Kendo MVC Grid Within a Window DataSource Read

I'm trying to populate a kendo grid within a kendo window in MVC and am unable to find what is wrong. The window is created, and the grid is created within the window... however the DataSource's Read method is never called.
Window:
#{
Html.Kendo().Window()
.Name("DListing")
.Title("Listing")
.Draggable()
.Resizable()
.Width(1000)
.Height(500)
.Visible(true)
.Modal(true)
.Actions(actions => actions
.Maximize()
.Close())
.LoadContentFrom("Dispatch", "Listing", new { Number = #ViewBag.Number })
.Render();}
The Dispatch method in the Listing controller returns back a partial view that contains the grid.
Grid:
#(Html.Kendo().Grid(Model)
.Name("Grid")
.Events(events => events.Change("onChange"))
.HtmlAttributes(new { style = "height:400px;" })
.Columns(columns =>
{
columns.Bound(p => p.Number);
columns.Bound(p => p.DateTime).Format("{0:MM/dd/yyyy hh:mm tt}");
columns.Bound(p => p.Location);
columns.Bound(p => p.Name);
columns.Bound(p => p.Elapsed_Hours);
})
.Groupable()
.Pageable(pageable => pageable
.Numeric(false)
.Input(true)
.PageSizes(new[] { 5, 10, 25 }))
.Sortable()
.Scrollable(scrollable => scrollable
.Virtual(true))
.Filterable()
.Selectable(selectable => selectable
.Mode(GridSelectionMode.Multiple))
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(13)
.Sort(sort => { sort.Add(p => p.DateTime).Descending(); })
.Model(model => { model.Id(p => p.Number); })
.Read(read => read.Action("Listing_Read", "Listing", new { Number = #ViewBag.Number })))
)
Listing_Read Method:
public ActionResult Listing_Read([DataSourceRequest] DataSourceRequest request, int Number)
{
return Json(GetListing(branchNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
Also, it should be noted that I went through and verified that the viewbag data is available for both the window and later on in the grid.
For a little more back info, I initially had the grid on it's own page and it was able to call the read method and populated with the data with no issues. After moving it to populate in the window is when this became a problem.
Monitoring the http requests, the grid never attempts to call the read method (so the request isn't failing). I tried manually refreshing the datasource after the window has loaded thinking that might force the call, but that doesn't call the read method either.
I've been scratching my head on this one for a few hours now trying different things, hoping someone can spot what the problem is :)
Here's what worked for me:
1) View (~/Views/Home/Index.cshtml)
#(Html.Kendo().Window()
.Name("myWindow")
.Title("Title")
.Actions(actions => actions.Pin().Minimize().Maximize().Close())
//.Content(Html.Partial("gridCat").ToHtmlString())
.LoadContentFrom("Load_gridCat", "Home")
)
2) Partial View (~/Views/Shared/gridCat.cshtml)
#(Html.Kendo().Grid<TelerikMvcApp1.Models.Category>()
.Name("CategoriesGrid")
.Columns(columns =>
{
columns.Bound(c => c.CategoryID).Title("Category").Width("10%");
columns.Bound(c => c.CategoryName);
columns.Bound(c => c.Description);
})
.Filterable()
.Pageable()
.Sortable()
.Scrollable()
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(p => p.CategoryID))
.Read(r => r.Action("Categories_Read", "Home"))
)
.HtmlAttributes(new { style = "height:250px" })
)
3) Controller (~/Controllers/HomeController.cs)
public ActionResult Load_gridCat()
{
return PartialView("gridCat");
}
public ActionResult Categories_Read([DataSourceRequest]DataSourceRequest request)
{
using (var ctx = new NWindContext())
{
IQueryable<Category> categories = ctx.Categories;
DataSourceResult result = categories.ToDataSourceResult(request);
return Json(result, JsonRequestBehavior.AllowGet);
}
}

Resources