How to pass object as parameter to kendo grid read method - kendo-grid

I have kendo grid as follow.
#(Html.Kendo().Grid<ManualInputDetail>()
.Name("gManualInputDetail")
.Columns(columns =>
{
columns.Bound(c => c.Id).Hidden(true);
columns.Bound(c => c.Month).Title("Month");
columns.Bound(c => c.Value).Title("Value");
})
.Editable(editable => editable.Mode(GridEditMode.InLine))
.Pageable()
.Navigatable()
.Selectable(selectable =>
{
selectable.Mode(GridSelectionMode.Single);
selectable.Type(GridSelectionType.Row);
})
.Sortable(sortable =>
{
sortable.SortMode(GridSortMode.MultipleColumn);
})
.DataSource(dataSource => dataSource
.WebApi()
.Model(model => model.Id(p => p.Id))
.PageSize(12)
.Read(read => read.Url(Url.HttpRouteUrl("ActionApi", new { controller = "ManualInputDetails", action = "GetManualInputDetails" })).Data("getFilterData"))
)
.Pageable(p => p.Refresh(true))
)
using getFilterData function I want to pass object parameter to read method. getFilterData function as follow
function getFilterData() {
var header= {
SectorId: 1,
BrandId: 2,
LocationId: 1,
DataElementId:2
}
return {
header: header
};
}
GetManualInputDataElements method as follow
[ActionName("GetManualInputDetails")]
public DataSourceResult GetManualInputDetails([System.Web.Http.ModelBinding.ModelBinder(typeof(WebApiDataSourceRequestModelBinder))] DataSourceRequest request,ManualInputHeader header)
{
var model = new DataElementMgt().GetAll(header).Select(x => new DataElement()
{
Id = x.Id,
DataElementTypeId = x.DataElementTypeId,
Name = x.Name,
Descriptionn = x.Descriptionn
}).ToList().ToDataSourceResult(request);
return model;
}
In here header value always gives as null. What is the reason for that. Is any thing wrong? Please help..

change the getFilterData method to this
function getFilterData() {
var _header= {
SectorId: 1,
BrandId: 2,
LocationId: 1,
DataElementId:2
}
return {
header: _header
};
}
and it should work. dont use the same name for what you return and declare.

Related

DEVEXTREME Save all selected data in grid inside edit form to database

multiple select item in Edit form with grid
How to save the data included the selected item at grid using DEVEXTREME.
The condition now is i can show the grid but now i struggle on get all the data inside the grid to save it and bring it to database, including need to show it again when the user want to edit the data
Template:
#using (Html.DevExtreme().NamedTemplate("EmbeddedDataGridMultiple"))
{
#(Html.DevExtreme().DataGrid()
.ID("PrincipalGrid")
.DataSource(d => d.WebApi().Controller("MasterPrincipal").LoadAction("GetPrincipalData").Key("PrincipalId"))
.Columns(columns => {
columns.Add().DataField("Principal");
columns.Add().DataField("Description");
})
.HoverStateEnabled(true)
.Paging(p => p.PageSize(10))
.FilterRow(f => f.Visible(true))
.Scrolling(s => s.Mode(GridScrollingMode.Virtual))
.Height(345)
.Selection(s => s.Mode(SelectionMode.Multiple))
.SelectedRowKeys(new JS(#"component.option(""value"")"))
.OnSelectionChanged(#<text>
function(selectedItems) {
var keys = selectedItems.selectedRowKeys;
component.option("value", keys);
}
</text>)
)
}
Form
#(Html.DevExtreme().DataGrid<MasterGroupQuotaValidateModel>
()
.ID("gridData")
.ShowBorders(true)
.DataSource(d => d.Mvc().Controller("MasterGroupQuota")
.LoadAction("GetGroupQuota")
.Key("IdGroup")
.UpdateAction("UpdateMasterGroupQuota")
.DeleteAction("DeleteMasterGroupQuota")
.InsertAction("InsertMasterGroupQuota")
)
.RemoteOperations(true)
.Columns(columns =>
{
columns.AddFor(m => m.RowNumber).Caption("No").Width(70);
columns.AddFor(m => m.GroupQuotaId).Visible(false);
columns.AddFor(m => m.SitePlan)
.Lookup(lookup => lookup
.DataSource(d => d.WebApi().Controller("MasterSite").LoadAction("GetSitePlan").Key("SiteId"))
.DisplayExpr("SitePlan")
.ValueExpr("SiteId")
).ValidationRules(rules =>
{
rules.AddAsync().ValidationCallback("CheckGroupQuota").Message("This Site is already registered with the follwoing GroupQuota and Principal");
}); ;
columns.AddFor(m => m.Description).Caption("Group Quota").ValidationRules(rules =>
{
rules.AddAsync().ValidationCallback("CheckGroupQuota").Message("This Group Quota is already registered with the follwoing Site Plan and Principal");
});
columns.AddFor(m => m.Principal)
.Lookup(lookup => lookup
.DataSource(d => d.WebApi().Controller("MasterPrincipal").LoadAction("GetPrincipalData").Key("PrincipalId"))
.DisplayExpr("Principal")
.ValueExpr("PrincipalId")
).ValidationRules(rules =>
{
rules.AddAsync().ValidationCallback("CheckGroupQuota").Message("This Principal is already registered with the follwoing GroupQuota and Site Plan");
});
})
.Paging(paging => paging.PageSize(5))
.Pager(pager =>
{
pager.Visible(true);
pager.ShowPageSizeSelector(true);
pager.AllowedPageSizes(new JS("[5, 10, 'all']"));
pager.ShowInfo(true);
pager.ShowNavigationButtons(true);
})
.Sorting(sorting=> sorting.Mode(GridSortingMode.Single))
.FilterRow(f => f.Visible(true))
.HeaderFilter(f => f.Visible(true))
.AllowColumnReordering(true)
.ShowBorders(true)
.Grouping(grouping => grouping.AutoExpandAll(true))
.SearchPanel(searchPanel => searchPanel.Visible(true))
.GroupPanel(groupPanel => groupPanel.Visible(true))
.HoverStateEnabled(true)
.ShowRowLines(true)
.RowAlternationEnabled(true)
.Scrolling(scrolling => scrolling.RowRenderingMode(GridRowRenderingMode.Virtual))
.Selection(s => s.Mode(SelectionMode.Single))
.OnSelectionChanged("gridSelectionChanged")
.OnExporting("exporting")
.OnRowUpdating("RowUpdating")
.OnEditorPreparing("onEditorPreparing")
.OnSaved("setItemTreeToTextSaving")
.OnEditingStart(#<text>
function(e) {
GetKeyId(e.key)
}
</text>)
.Editing(e => e.Mode(GridEditMode.Popup)
.AllowUpdating(false)
.AllowAdding(false)
.AllowDeleting(false)
.UseIcons(true)
.Popup(p => p
.ShowTitle(true)
.Width(700)
.Height(525)
)
.Form(f => f.Items(items =>
{
items.AddGroup()
.Caption("Detail Group Quota")
.ColCount(2)
.ColSpan(2)
.Items(groupItems =>
{
groupItems.AddSimpleFor(m => m.GroupQuotaId).Visible(false);
groupItems.AddSimpleFor(m => m.SitePlan);
groupItems.AddSimpleFor(m => m.Description);
});
items.AddGroup()
.Caption("Principal")
.ColCount(2)
.ColSpan(2)
.Items(groupItems =>
{
groupItems.AddSimpleFor(m => m.Principal).Template(new TemplateName("EmbeddedDataGridMultiple")).ColSpan(2);
});
}))
)
)

Populating ASP.NET MVC Kendo Grid Via Ajax Call

I have an MVC Kendo Grid and I want to fill it via a jQuery Ajax Call. I used jQuery 'each' method to do it like this :
function FillRowsByRequest(reqRow) {
var readDataUrl = '#Url.Action("GetGoodsByReq")';
var targetGrid = $("#storeReceiptRowsGrid").data("kendoGrid");
$.get(readDataUrl, { reqseq: reqRow }, function (d, t, j) {
var counter = 0;
targetGrid.cancelChanges();
$(d).each(function (i, e) {
targetGrid.dataSource.insert(counter++, {
GOOD_ID: e.GOOD_ID,
GOOD_CODE: e.GOOD_CODE,
GOOD_CODE_DESC: e.GOOD_CODE_DESC,
GOOD_DESC: e.GOOD_DESC
});
});
});
}
I can see my Kendo Grid that is filled with data ( not completely ) but the thing is that when I click on the Save button, it does not trigger the Save Action Method and consequently nothing is inserted in the table and Grid contains nothing after it is refreshed.
#(Html.Kendo()
.Grid<Tpph.Models.STORE_RECEIPT_ROW>()
.Name("storeReceiptRowsGrid")
.Columns(columns =>
{
columns.Bound(o => o.GOOD_ID).Title("Good ID").HtmlAttributes(new { #class = "goodid" }).Visible(false);
columns.Bound(o => o.GOOD_CODE).Title("Good Code").HtmlAttributes(new { #class = "goodcode" }).Width(100);
columns.Bound(o => o.GOOD_CODE_DESC).Title("Good Code Desc").HtmlAttributes(new { #class = "goodcodedesc" }).Width(100);
columns.Bound(o => o.GOOD_DESC).Title("Good Desc").HtmlAttributes(new { #class = "gooddesc" }).Width(155);
})
.ToolBar(toolbar =>
{
toolbar.Create().Text("New Row").HtmlAttributes(new { #class = "k-primary", style = "background-color: #e6ffe6; border-color: #10c4b2; min-width: 100px; color: black;" });
toolbar.Save().Text("Save").SaveText("Save").CancelText("Cancel").HtmlAttributes(new { #class = "k-primary", style = "background-color: #e6ffe6; border-color: #10c4b2; min-width: 100px; color: black;" });
})
.ColumnMenu()
.Selectable(s => s.Type(GridSelectionType.Row))
.Sortable()
.Editable(editable => editable.Mode(GridEditMode.InCell).DisplayDeleteConfirmation("Delete?"))
.Filterable()
.Groupable()
.Scrollable()
.Pageable(p => p.Refresh(true))
.Resizable(resize => resize.Columns(true))
.Reorderable(reorder => reorder.Columns(true))
.DataSource(dataSource => dataSource
.Ajax()
.Events(ev => ev.RequestEnd("storeReceiptRowsGridOnRequestEnd"))
.Batch(true)
.ServerOperation(true)
.Model(model =>
{
model.Id(p => p.GOOD_ID);
})
.Read(read => read.Action("StoreReceiptRowsRead", "StorageForms"))
.Update(u => u.Action("StoreReceiptRowsEdit", "StorageForms"))
.Create(c => c.Action("StoreReceiptRowsCreate", "StorageForms"))
.Destroy(de => de.Action("StoreReceiptRowsDestory", "StorageForms")))
.Events(ev =>
{
ev.DataBound("storeReceiptRowsGridOnBound");
})
)
How can I do this ?
After lots of struggling with this issue, I finally found out that the Kendo Grid triggers the CRUD Action Methods only when the "dirty" attribute of a row is set to true. ( dirty flag is a tiny little red triangle which appears in the corner of a cell when you edit that cell ). So the solution to this issue is setting dirty flag of each row to true like this :
.set("dirty", true);
So my final JavaScript Code is like this :
function FillRowsByRequest(reqRow) {
var readDataUrl = '#Url.Action("GetGoodsByReq")';
var targetGrid = $("#storeReceiptRowsGrid").data("kendoGrid");
$.get(readDataUrl, { reqseq: reqRow }, function (d, t, j) {
var counter = 0;
targetGrid.cancelChanges();
$(d).each(function (i, e) {
targetGrid.dataSource.insert(counter++, {
GOOD_ID: e.GOOD_ID,
GOOD_CODE: e.GOOD_CODE,
GOOD_CODE_DESC: e.GOOD_CODE_DESC,
GOOD_DESC: e.GOOD_DESC
}).set("dirty", true);
});
});
}

Error event handling causes Read to not be called

Below is my PartialView for a Kendo Grid. As of now, my Parts_Read action is NOT called. But, if I comment out
.Events(events => events.Error("error_handler"))
Then everything works fine. Any ideas of why this is happening?
#using Kendo.Mvc.UI;
#using eRPortalDashboard.Models
#model PMPartsViewModel
#{
int PMNumber = Model.PMNumber;
string uniqueName = Model.PartsGrid.ID;//Regex.Replace(Guid.NewGuid().ToString(), "[^A-Za-z]+", "");
bool enableToolbar = Model.PartsGrid.EnableToolbar;
bool enablePageable = Model.PartsGrid.Pageable;
bool enableSortable = Model.PartsGrid.Sortable;
bool enableColumnMenu = Model.PartsGrid.EnableColumnMenu;
bool enableGroupable = Model.PartsGrid.Groupable;
bool enableColumnResizing = Model.PartsGrid.AllowColumnResizing;
bool enableScrolling = Model.PartsGrid.Scrollable;
bool enableSelection = Model.PartsGrid.Selectable;
}
#(Html.Kendo().Grid<PartViewModel>()
.Name(uniqueName)
.Columns(columns =>
{
columns.Bound(c => c.ItemNumber);
columns.Bound(c => c.Description);
})
.ToolBar(toolBar =>
{
toolBar.Custom().Text("Test Button").Url("#").HtmlAttributes(new { id = "testButton" });
})
.Pageable(pager => pager
.Input(false) //Using pageable.numeric and pageable.input at the same time is not recommended.
.Numeric(true)
.Info(true)
.PreviousNext(true)
.Refresh(true)
.PageSizes(new object[] { 5, 10, 20, 50, "all" })
.Enabled(enablePageable)
)
.Selectable(s => s.Mode(mode: GridSelectionMode.Multiple).Enabled(enableSelection))
.AllowCopy(enableSelection) //selectable needs to be enabled and set to multiple
.Sortable(s => s.SortMode(GridSortMode.MultipleColumn).Enabled(enableSortable))
.ColumnMenu(c => c.Enabled(enableColumnMenu))
.Groupable(g => g.Enabled(enableGroupable))
.Scrollable(s => s.Height("auto").Enabled(enableScrolling))
.Resizable(resize => resize.Columns(enableColumnResizing))
//.Events(events => events.DataBound(uniqueName + "_updateGrid").Change(uniqueName + "_updateGrid"))
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(true)
.Events(events => events.Error("error_handler"))
.Read("Parts_Read", "PM", new { PMNumber = PMNumber })
)
)
<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);
}
}
The main crux of my issue was the fact that error_handler was declared after my MVC code, thereby making it unable to bind to the method.
Apparently, with Kendo (maybe others), when using Partial Views, the javascript function must be declared BEFORE it is used in Razor syntax for that view.
see also: telerik forum post

Kendo Grid Read Action Not Passing Data To Controller Via the .Data Method Call

I have a Kendo Grid (MVC Razor) that I am trying to have pass extra data to the controller via the .Data call off of the Read method:
#(Html.Kendo().Grid<AssignedSiteGridPoco>()
.Name("UnAssignedSiteGrid")
.Filterable()
.Sortable()
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5))
.Columns(columns =>
{
columns.Bound(p => p.SiteId).Hidden();
columns.Bound(p => p.SiteName).Title("Site Name").Width(180);
columns.Bound(p => p.City).Title("City").Width(80);
columns.Bound(p => p.StateName).Title("State Name").Width(100);
columns.Command(command => command
.Custom("Add")
.Click("unassignedSiteGridClick")
).Width(90);
})
.Scrollable()
.Selectable(selectable => selectable.Mode(GridSelectionMode.Single))
.Resizable(resize => resize.Columns(true))
.Events(events =>
{
//events.Change("GridChange");
//events.DataBound("OnDataBound");
})
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(p => p.SiteId);
model.Field(p => p.SiteName);
model.Field(p => p.City).Editable(false);
model.Field(p => p.StateName).Editable(false);
})
.PageSize(15)
.Read(read => read.Action("GetUnassignedSiteGridDataList", "Manager").Data("getUserRightName"))
))
The Javascript block, placed above the grid div, is as follows:
function getUserRightName() {
return
{
UserRightName : "2"
};
}
And the controller:
public JsonResult GetUnassignedSiteGridDataList([DataSourceRequest]DataSourceRequest request, string UserRightName)
{
var model = new AssignedSiteGridPoco();
var siteList = _managerPresentationService.GetUnassignedSiteGridDataList(model);
return Json(siteList.ToDataSourceResult(request));
}
The string value being passed from the view's read method is null in the "UserRightName" string. According to the examples, it should pass back the text value "2" My Version of Kendo is: 2014.2.807 InternalBuild. Is there a problem in this build in this area?
Thanks,
Steven
Wrap the key name in the json structure into quotes i.e.
change your js function to this:
function getUserRightName() {
return {'UserRightName':"2"};
}

kendo mvc grid updating

I am new to asp.net mvc so i have some problems with kendo mvc grid.
here my model:
public class LessonsDep
{
public int LesId { get; set; }
public int Activated { get; set; }
public string TaskTable { get; set; }
}
public class LessonsBusinessLayer
{
public void changeLessons(LessonsDep lessons){
string connectionString = ConfigurationManager.ConnectionStrings["nisa1415"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("dep.edidBiology",con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramId = new SqlParameter();
paramId.ParameterName = "#LesId";
paramId.Value = LessonNameClass.stcLesId;
cmd.Parameters.Add(paramId);
SqlParameter paramActivated = new SqlParameter();
paramActivated.ParameterName = "#Activated";
paramActivated.Value = lessons.Activated;
cmd.Parameters.Add(paramActivated);
SqlParameter paramTaskTable = new SqlParameter();
paramTaskTable.ParameterName = "#TaskTable";
paramTaskTable.Value = lessons.TaskTable;
cmd.Parameters.Add(paramTaskTable);
con.Open();
cmd.ExecuteNonQuery();
}
}
}
///----------------------------------------------------------------///
the view:
#model IEnumerable<BusinessLayer.LessonsDep>
<div id="clientsDb">
#(Html.Kendo().Grid(Model)
.Name("grid")
.Scrollable()
.Columns(columns =>
{
columns.Bound(c => c.LesId).Width(140);
columns.Bound(c => c.Activated).Width(50);
columns.Bound(c => c.TaskTable).Width(300);
})
.HtmlAttributes(new { style = "height: 500px;" })
.Sortable()
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5))
.ToolBar(toolbar =>
{
toolbar.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(false)
.Events(events => events.Error("error_handler"))
.Model(model => model.Id(c => c.LesId))
.Read("Editing_Read", "LessonController")
.Update("Editing_Update", "Lesson")
)
)
/-------------------------------------------------------/
and the controller :
public ActionResult Index2()
{
LessonsBusinessLayer lessonsBusinessLayer = new LessonsBusinessLayer();
List<LessonsDep> lessons = lessonsBusinessLayer.LessonsDeps.ToList();
string myString = LessonNameClass.LessonsName;
return View(lessons);
}
here i want to add method that shoul update data:
public ActionResult Editing_Update()
{
//.......Can I call ChangeLesson() Method from LessonsBusinessLayer?
//if answer is: yes then How i should call this method?
return View();
}
You have to change
.Editable(editable => editable.Mode(GridEditMode.InCell))
to
.Editable(editable => editable.Mode(GridEditMode.InLine))
Write Controller as per below..
Controller
public JsonResult SaveAccountAdmin([DataSourceRequest]DataSourceRequest request,CompanyContactModel companyContactModel)
{
If error: ModelState.AddModelError(string.Empty, e.Message);
DataSourceResult result = [Your Model List].ToDataSourceResult(request, ModelState);
return Json(result, JsonRequestBehavior.AllowGet);
}
I hope this help you..
Hey guys I found what's the problem of programm. I post my answer here , maybe it will help to someone. So answer is here: 1. as i understood my data is server binding (not ajax):
SqlCommand cmd = new SqlCommand("dep.edidBiology",con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramId = new SqlParameter();
paramId.ParameterName = "#LesId";
paramId.Value = LessonNameClass.stcLesId;
cmd.Parameters.Add(paramId);
so i need to change code in view from this:
#(Html.Kendo().Grid(Model)
.Name("grid")
.Scrollable()
.Columns(columns =>
{
columns.Bound(c => c.LesDepId).Width(140);
columns.Bound(c => c.TeId).Width(300);
columns.Bound(c => c.GradeId).Width(300);
columns.Bound(c => c.Activated).Width(100);
columns.Bound(c => c.GroupId).Width(300);
columns.Bound(c => c.TaskTable).Width(300);
columns.Command(command => command.Edit()).Width(200);
})
.HtmlAttributes(new { style = "height: 500px;" })
.Sortable()
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5))
.Editable(editable => editable.Mode(GridEditMode.InLine))
.DataSource(dataSource => dataSource
*.Ajax()*
*.ServerOperation(false)*
.Model(model => model.Id(c => c.LesId))
.Read("Index2", "Lesson")
.Update("Editing_Update", "Lesson")
)
)
to this:
#(Html.Kendo().Grid(Model)
.Name("grid")
.Scrollable()
.Columns(columns =>
{
columns.Bound(c => c.LesDepId).Width(140);
columns.Bound(c => c.TeId).Width(300);
columns.Bound(c => c.GradeId).Width(300);
columns.Bound(c => c.Activated).Width(100);
columns.Bound(c => c.GroupId).Width(300);
columns.Bound(c => c.TaskTable).Width(300);
columns.Command(command => command.Edit()).Width(200);
})
.HtmlAttributes(new { style = "height: 500px;" })
.Sortable()
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5))
.Editable(editable => editable.Mode(GridEditMode.InLine))
.DataSource(dataSource => dataSource
*.Server()*
*.ServerOperation(false)*------>>>>> delete this line
.Model(model => model.Id(c => c.LesId))
.Read("Index2", "Lesson")
.Update("Editing_Update", "Lesson")
)
)
and my controller that receives data from kendo grid looks like:
public ActionResult Index()
{
LessonsBusinessLayer lessonsBusinessLayer = new LessonsBusinessLayer();
List<LessonsDep> lessons = lessonsBusinessLayer.LessonsDeps.ToList();
return View(lessons);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Editing_Update([DataSourceRequest] DataSourceRequest request, LessonsDep product)
{
if (product != null && ModelState.IsValid)
{
LessonsBusinessLayer lessonsBusinessLayer = new LessonsBusinessLayer();
lessonsBusinessLayer.changeLessons(product);
return RedirectToAction("Index");
}
return View();
}