Kendo Grid dynamic columns and update the batch Values - datatable

I have dynamic column in Kendo Grid through dynamic datatable, Everything is fine,
the problem is that, Kendo grid doesn't update the batch changing values in controller. plz look following, kindly help me.
#model System.Data.DataTable
#(Html.Kendo().Grid<dynamic>()
.Name("GridfilterHandler")
.Columns(columns =>
{
foreach (System.Data.DataColumn column in Model.Columns)
{
var c = columns.Bound(column.ColumnName).EditorTemplateName("gridColumn");
if (column.ColumnName == "ShowCheck")
{
columns.Template(#<text></text>).ClientTemplate("<input type='checkbox' #= ShowCheck ? checked='checked':'' # class='chkbx' />")
.HeaderTemplate("<input type='checkbox' id='masterCheckBox' onclick='checkAll(this)'/>").Width(200);
}
}
columns.Command(cmd => cmd.Edit());
})
.Pageable()
.Sortable()
.ToolBar(toolbar =>
{
toolbar.Save();
})
.Editable(ed => ed.Mode(GridEditMode.InCell))
// .Events(events => events.SaveChanges("onSaveChanges"))
.Filterable()
.Groupable()
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
foreach (System.Data.DataColumn column in Model.Columns)
{
model.Field(column.ColumnName, column.DataType);
}
})
.Model(model =>
{
var id = Model.PrimaryKey[0].ColumnName;
model.Id(id);
foreach (System.Data.DataColumn column in Model.Columns)
{
model.Field(column.ColumnName, column.DataType);
// var field = model.Field(column.ColumnName, column.DataType);
}
})
.Batch(true)
.Read(read => read.Action("readfilterHandlerGrid", "Customize", new { filterTitle = Request.QueryString["filterTitle"] }))
.Update(update => update.Action("updatefilterHandlerGrid", "Customize"))
)
)
public ActionResult updatefilterHandlerGrid([DataSourceRequest] DataSourceRequest request, IEnumerable<dynamic> items)
{...............
}
public ActionResult updatefilterHandlerGrid([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")] IEnumerable<DataTable> products)
{.......................
}
I have tried above update events, but i get null values.

public ActionResult Update([DataSourceRequest] DataSourceRequest request, FormCollection model)
{
foreach (var key in model.Keys)
{
//Build you update query here
}
Here the Solution

Related

How to get querystring value to Kendo Grid update method and pass to MVC controller

I have a kendo grid and need to get a querystring value. See below code.
Browser Url = http://blahblah/blah/36?EvaluationCriteriaGrid-mode=edit&chiefEvalCriteriaId=110
UI.cshtml
#(Html.Kendo().Grid(Model.ChiefEvaluationCriteriaList.AsEnumerable())
.Name("EvaluationCriteriaGrid")
.Columns(columns =>
{
columns.Bound(p => p.EvaluationCriteriaName);
columns.Bound(p => p.MinScore).Width(100).Title("Min Score").Format("{0:0}");
columns.Bound(p => p.MaxScoreDisplay).Width(100).Title("Max Score");
columns.Command(command => { command.Edit(); }).Width(180).Title("Action");
})
.CellAction(cell =>
{
if (cell.Column.Title == "Action")
{
if (cell.DataItem.EvaluationResultID ==
ServiceProxy.Model.DomainConstants.EVALUATION_RESULT_APPROVED)
{
cell.HtmlAttributes["style"] = "display:none;";
}
}
})
.Editable(editing => editing.Mode(GridEditMode.InLine))
.Pageable()
.Sortable()
.Scrollable()
.DataSource(dataSource => dataSource
.Server()
.Model(model => model.Id(c => c.ChiefEvaluationCriteriaID))
.Read("EvaluationQuestionnaire", "EvaluationCriteria", new { area = "Proposal", Id = Model.SolicitationDetails.SolicitationID })
.Update("EditEvaluationCriteria", "EvaluationCriteria", new { area = "Proposal", Id = Model.SolicitationDetails.SolicitationID })
)
)
Controller.cs
[HttpPost]
public ActionResult EditEvaluationCriteria( int Id, int chiefEvalCriteriaId, int maxScoreDisplay, int minScoreDisplay = 0 )
{
if (ModelState.IsValid)
{
Do something
}
return view
}
Thank you for the support

How to display data from database into Kendo Grid

I want to display my data from database to kendo grid but the result is no display. I don't know what happen can you see correct my code if there's wrong syntax for display my data into kendo grid. I try so many solution but my problem is still the same and here is my Code in Controller
namespace TBSWebApp.Controllers
{
public class LoanApplicationController : Controller
{
// GET: LoanApplication
public ActionResult LoanApplication()
{
return View();
}
public static List<DisplayRecords> objCmp = new List<DisplayRecords>();
static LoanApplicationController()
{
string strServer = GlobalVariable.prServer;
string strDatabase = GlobalVariable.prDatabase;
string mainconn = string.Format(ConfigurationManager.ConnectionStrings["BackendEntities"].ConnectionString, strServer, strDatabase);
SqlConnection sqlconn = new SqlConnection(mainconn);
string s1 = "SELECT InvoiceNo,InvoiceDate,FileAs,LoanBalance FROM tblInvoice LEFT OUTER JOIN tblContacts ON tblInvoice.CustomerID = tblContacts.ContactID WHERE LEFT(InvoiceNo,2) ='LR'";
SqlCommand sqlcomm = new SqlCommand(s1);
sqlcomm.Connection = sqlconn;
sqlconn.Open();
SqlDataReader sdr = sqlcomm.ExecuteReader();
List<DisplayRecords> objmodel = new List<DisplayRecords>();
if (sdr.HasRows)
{
while (sdr.Read())
{
objCmp.Add(new DisplayRecords { InvoiceNo = sdr["InvoiceNo"].ToString(), InvoiceDate =Convert.ToDateTime(sdr["InvoiceDate"].ToString()), FileAs = sdr["FileAs"].ToString(), Amount = sdr["LoanBalance"].ToString() });
}
sqlconn.Close();
}
}
public ActionResult GetData([DataSourceRequest] DataSourceRequest dsRequest)
{
var result = objCmp.ToDataSourceResult(dsRequest);
return Json(result);
}
public ActionResult UpdateData([DataSourceRequest] DataSourceRequest dsRequest, DisplayRecords person)
{
if (person != null && ModelState.IsValid)
{
var toUpdate = objCmp.FirstOrDefault(p => p.InvoiceNo == person.InvoiceNo);
TryUpdateModel(toUpdate);
}
return Json(ModelState.ToDataSourceResult());
}
}
}
and this is my code in view LoanApplication.cshtml for my design in kendo grid
<div class="row">
<div style="width:100%;height:100%">
#(Html.Kendo().Grid<TBSWebApp.Models.DisplayRecords>().Name("LoanApplication")
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(m => m.InvoiceNo))
.Read(read => read.Action("GetData", "LoanApplication"))
.Update(up => up.Action("UpdatePerson", "LoanApplication"))
)
.Columns(columns =>
{
columns.Bound(c => c.InvoiceNo).Width(200);
columns.Bound(c => c.InvoiceDate);
columns.Bound(c => c.FileAs);
columns.Bound(c => c.Amount);
columns.Command(cmd => cmd.Edit());
})
.Pageable()
.Sortable()
.Editable(ed => ed.Mode(GridEditMode.PopUp).TemplateName("Person"))
)
</div>
and i don't think if there is wrong with my code in here . Can you enlighten me if I have something to config in some other settings, not just in controller and view and the below is the image of the result
and the below is my data from sql server:

Kendo Grids ClientTemplate for ForeignKey column not displaying chosen value?

Using MVC, I am trying to implement inline-editing of a Kendo Grid using a Foreign Key Column...which should display & save a chosen value from it's relevant ComboBox.
Editing works...but it doesn't display the chosen value upon UPDATING the row.
What am I doing wrong?
MY VIEW CONTROL LOOKS LIKE:
#(Html.Kendo().Grid<RTUDeviceCustomRegisterModbus>()
.Columns(columns =>
{
columns.Bound(x => x.Id)
.Visible(false);
columns.Bound(x => x.RTUDeviceId)
.Visible(false);
columns.Bound(x => x.Register)
.Title("Register")
.Width(50);
columns.Bound(x => x.Description)
.Title("Description")
.Width(100);
columns.ForeignKey(x => x.DataUnitId, Model.DataUnits, "Id", "DataUnitName")
.ClientTemplate((#Html.Kendo().ComboBox()
.BindTo(Model.DataUnits)
.Name("ddlDataUnits_#=Id#")
.DataValueField("Id")
.DataTextField("DataUnitName")
.ToClientTemplate()).ToHtmlString())
.Title("Units")
.Width(50);
columns.ForeignKey(x => x.DataTypeId, Model.DataTypes, "Id", "DataTypeName")
.Title("Data Type")
.Width(50);
columns.Bound(x => x.DataTypeSize)
.Title("ASCII (size)")
.Width(50);
columns.Command(command => { command.Edit(); command.Destroy(); }).Width(100);
})
.Name("gridCustomRegisterModbus")
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.InLine))
.Sortable()
.Scrollable()
.BindTo(Model.RTUDeviceCustomRegisterModbuses)
.DataSource(dataSource => dataSource.Ajax()
.ServerOperation(true)
.PageSize(50)
.Model(model => { model.Id(m => m.Id); })
.Create(update => update.Action("Create", "CustomRegisterModbus", new { Area = "Documents" }))
.Update(update => update.Action("Update", "CustomRegisterModbus", new { Area = "Documents" }))
.Destroy(update => update.Action("Destroy", "CustomRegisterModbus", new { Area = "Documents" }))
)
.HtmlAttributes(new { #class = "", #style = "height: 400px;" }))
MY ACTION LOOKS LIKE:
Yes, it calls the action...but the DataUnitId is NULL. So, I am guessing I need the client template for that part...but that isn't working.
public class CustomRegisterModbusController : BaseController
{
#region <Actions>
[HttpPost]
public ActionResult Create([DataSourceRequest] DataSourceRequest request, RTUDeviceCustomRegisterModbus entity)
{
// It makes the call to CREATE...but the value of the ID is null
return Json(new[] { entity }.ToDataSourceResult(request, ModelState));
}
[HttpPost]
public ActionResult Update([DataSourceRequest] DataSourceRequest request, RTUDeviceCustomRegisterModbus entity)
{
// Do awesome stuff
return Json(new[] { entity }.ToDataSourceResult(request, ModelState));
}
[HttpPost]
public ActionResult Destroy([DataSourceRequest] DataSourceRequest request, RTUDeviceCustomRegisterModbus entity)
{
// Do awesome stuff
return Json(new[] { entity }.ToDataSourceResult(request, ModelState));
}
#endregion
}
I hate to answer my own question, but here it is...
I needed a client-side method to handle Grid.Save
This method would sets any chosen DROP DOWN LIST value into the model
I tried all kinds of other posted solutions...this is the ONLY thing that worked.
THE FINAL RAZOR MARKUP LOOKS LIKE:
#(Html.Kendo().Grid<RTUDeviceCustomRegisterModbus>()
.Columns(columns =>
{
columns.Bound(x => x.Id)
.Visible(false);
columns.Bound(x => x.RTUDeviceId)
.Visible(false);
columns.Bound(x => x.Register)
.Title("Register")
.Width(50);
columns.Bound(x => x.Description)
.Title("Description")
.Width(100);
columns.ForeignKey(x => x.DataUnitId, Model.DataUnits, "Id", "DataUnitName")
.Title("Units")
.Width(50);
columns.ForeignKey(x => x.DataTypeId, Model.DataTypes, "Id", "DataTypeName")
.Title("Data Type")
.Width(50);
columns.Bound(x => x.DataTypeSize)
.Title("ASCII (size)")
.Width(50);
columns.Command(command => { command.Edit(); command.Destroy(); }).Width(100);
})
.Name("gridCustomRegisterModbus")
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.InLine))
.Sortable()
.Scrollable()
.BindTo(Model.RTUDeviceCustomRegisterModbuses)
.DataSource(dataSource => dataSource.Ajax()
.ServerOperation(true)
.PageSize(50)
.Model(model => { model.Id(m => m.Id); })
.Create(update => update.Action("Create", "CustomRegisterModbus", new { Area = "Documents" }))
.Update(update => update.Action("Update", "CustomRegisterModbus", new { Area = "Documents" }))
.Destroy(update => update.Action("Destroy", "CustomRegisterModbus", new { Area = "Documents" }))
)
.HtmlAttributes(new { #class = "", #style = "height: 400px;" }))
THE JAVASCRIPT METHOD LOOKS LIKE:
Of course, you will probably put the method in your own 'controller' class
If you use Razor to bind to the GRIDS event...
.Events(events => events.Save("onSave"))
If you use a Custom JavaScript Controller to bind the event...
// Instances
var grid = $('#mygrid').data('kendoGrid');
// Bindings
grid.bind('save', onSave);
// Of course you would point to a custom Object
function onSave(e) {
var model = e.model;
var ddl = null;
var text = null;
// DataUnits
ddl = $(e.container.find('[data-role=dropdownlist]')[0]).data('kendoDropDownList');
text = ddl.value();
if (text !== null && text.length > 0) {
//model.DataUnitId = 0;
model.set('DataUnitId', text);
}
// DataTypes
ddl = $(e.container.find('[data-role=dropdownlist]')[1]).data('kendoDropDownList');
text = ddl.value();
if (text !== null && text.length > 0) {
//model.DataTypeId = 0;
model.set('DataTypeId', text);
}
}

kendo grid data depending on another kendo grid results UI for Asp.Net MVC

I Have two Kendo Grids (UI for Asp.Net MVC) on my page. The first grid gets results from database using an action method of a controller which is bound at grid initialization(I guess). The second grid should get the results of a column from first grid and pass as parameters to second grid which should pass these to action method of another controller bound to second grid. I tried to use autobind(false) but has no use. Please suggest.
Please try with the below code snippet.
VIEW
#(Html.Kendo().Grid<MvcApplication1.Models.TestModel>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(e => e.ID);
columns.Bound(e => e.Name);
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("GetData", "Home"))
)
.Events(events => events.Change("onChange"))
.Selectable(selectable => selectable
.Mode(GridSelectionMode.Single))
)
#(Html.Kendo().Grid<MvcApplication1.Models.ChildModel>()
.Name("ChildGrid")
.Columns(columns =>
{
columns.Bound(e => e.ChildID);
columns.Bound(e => e.ChildName);
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("GetChildData", "Home").Data("GetData"))
)
)
<script>
var ID = 0;
var Name = "";
function onChange(arg) {
ID = this.dataItem(this.select()).ID;
Name = this.dataItem(this.select()).Name;
$('#ChildGrid').data('kendoGrid').dataSource.read();
$('#ChildGrid').data('kendoGrid').refresh();
}
function GetData() {
return {
ID: ID,
Name: Name
};
}
</script>
CONTROLLER
public ActionResult GetChildData([DataSourceRequest] DataSourceRequest request, int ID, string Name)
{
List<ChildModel> lst = new List<ChildModel>();
if (ID == 0)
{
return Json(lst.ToDataSourceResult(request));
}
string str = ":" + ID + "_" + Name;
lst.Add(new ChildModel() { ChildID = 1, ChildName = "Name1" + str });
lst.Add(new ChildModel() { ChildID = 2, ChildName = "Name2" + str });
lst.Add(new ChildModel() { ChildID = 3, ChildName = "Name3" + str });
return Json(lst.ToDataSourceResult(request));
}
public ActionResult GetData([DataSourceRequest] DataSourceRequest request)
{
List<TestModel> lst = new List<TestModel>();
lst.Add(new TestModel() { ID = 1, Name = "Name1", MyDate = DateTime.Now });
lst.Add(new TestModel() { ID = 2, Name = "Name2", MyDate = DateTime.Now });
lst.Add(new TestModel() { ID = 3, Name = "Name3", MyDate = DateTime.Now });
return Json(lst.ToDataSourceResult(request));
}
MODEL
namespace MvcApplication1.Models
{
public class TestModel
{
public int ID { get; set; }
public string Name { get; set; }
[DataType(DataType.DateTime)]
public DateTime? MyDate { get; set; }
}
public class ChildModel
{
public int ChildID { get; set; }
public string ChildName { get; set; }
}
}
Let me know if any concern.
I have done something like that in my project. I've searched a lot and I finally realize that the solution is creating master and detail grids, the first gird will be the master and the second which get information from the first is detail, in my example is have two grid, one for Sport Branch and the other is for Federation. Federation get information from Sport Branch.
The Sport Branch grid:
<div >
#(Html.Kendo().Grid<SportBranchViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.SportBranchTitle).Title("Title").Width(120);
columns.Command(command => { command.Edit().Text("Edit").UpdateText("OK").CancelText("Cancel");
command.Destroy().Text("Delete");
})
.Width(172);
})
.ToolBar(toolbar => toolbar.Create().Text("Create"))
.Editable(editable =>
{
editable.Mode(GridEditMode.InLine);
editable.DisplayDeleteConfirmation("Are you sure you want to delete");
})
.Scrollable()
.Sortable(sortable => sortable.AllowUnsort(true))
.ClientDetailTemplateId("federationtemplate")
.DataSource(dataSource => dataSource
.Ajax()
.Events(events => events.Error("onError"))
.Model(model => model.Id(p => p.SportBranchID))
.Read(read => read.Action("SportBranch_Read", "BaseData"))
.Update(update => update.Action("SportBranch_Update", "BaseData"))
.Create(create => create.Action("SportBranch_Create", "BaseData"))
.Destroy(destroy => destroy.Action("DeleteSportBranch", "BaseData"))
)
.Events(events => events.DataBound("collapseGrid"))
.HtmlAttributes(new { style = "height:400px;" }))
</div>
the Federation grid:
<script id="federationtemplate" type="text/kendo-tmpl">
#(Html.Kendo().Grid<SportBranchFederationViewModel>()
.Name("grid_#=SportBranchID#")
.Columns(columns =>
{
columns.Bound(p => p.FederationName).Title("Title").Width(200);
columns.Command(command =>
{
command.Edit().Text("Edit").UpdateText("OK").CancelText("Cancel");
command.Destroy().Text("Delete");
})
;
})
.ToolBar(toolbar =>
{
toolbar.Create().Text("Create");
}
)
.Editable(editable =>
{
editable.Mode(GridEditMode.InLine);
editable.DisplayDeleteConfirmation("Are you sure you want to delete?");
})
.Scrollable()
.Sortable(sortable => sortable.AllowUnsort(true))
.Pageable()
.Events( e=> e.DataBound("onDataBoundFederation"))
.DataSource(dataSource => dataSource
.Ajax()
.Events(events => events.Error("onError"))
.Model(model => model.Id(p => p.FederationID))
.Read(read => read.Action("SportBranchFederation_Read", "BaseData", new { sportBranchID = "#=SportBranchID#" }))
.Create(create => create.Action("SportBranchFederation_Add", "BaseData", new { sportBranchID = "#=SportBranchID#" }))
.Update(update => update.Action("SportBranchFederation_Update", "BaseData", new { sportBranchID = "#=SportBranchID#" }))
.Destroy(destroy => destroy.Action("SportBranchFederation_Destroy", "BaseData", new { sportBranchID = "#=SportBranchID#" }))
.PageSize(7)
)
.HtmlAttributes(new { style = "height:250px;" })
.ToClientTemplate()
)
</script>
in the controller:
public ActionResult SportBranchFederation_Read(int sportBranchID , [DataSourceRequest] DataSourceRequest request)
{
var data = _bvaDataService.GetFederations(sportBranchID);
return Json(CreateSportBranchFederationsFromFederations(data.ToList()).ToDataSourceResult(request));
}
Here is the steps:
put the second grid in a script tag and specify an id for the script tag.
In the first grid use the ClientDetailTemplateId() and pass the id of script tag which enclose the second grid.
In the action of second grid which you want pass the value of a column of the first gird use the expression "#= [column's name of the first grid]#" (here is "#=SportBranchID#"). Note the "#= #" can use in grid to use a value of a field from the current grid or another. I send this field to my read action to get the corresponding result( look at my controller)
adding ToClientTemplate() to the second grid
read these samples too :
http://demos.telerik.com/kendo-ui/grid/detailtemplate ,
http://demos.telerik.com/aspnet-mvc/grid/detailtemplate

Saving a new product into database using Kendo UI Grid

I created a Create Action in Controller for saving new product into database. I saved it already but when I click Refresh button, it didn't save on Kendo Grid, either database.
public ActionResult Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<ProductDTO> products)
{
var results = new List<ProductDTO>();
if (products != null && ModelState.IsValid)
{
foreach (var product in products)
{
var create = db.Products.First(c => c.ProductID == product.ProductID);
results.Add(product);
db.SaveChanges();
}
}
return Json(results.ToDataSourceResult(request, ModelState));
}
EDIT
Kendo View:
#(Html.Kendo().Grid(Model)
.Name("Products")
.Columns(c =>
{
c.Command(p => p.Edit()).Width(170);
c.Bound(p => p.ProductID);
c.Bound(p => p.Name);
c.Bound(p => p.ListPrice);
c.Bound(p => p.ProductNumber);
c.Bound(p => p.Color);
c.Bound(p => p.StandardCost);
c.Command(p => p.Destroy()).Width(100);
}
)
.ToolBar(tb =>
{
tb.Create();
tb.Save();
})
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5))
.Sortable()
.Editable(e => e.Mode(GridEditMode.InCell))
.DataSource(d => d .Ajax()
.Batch(true)
.Model(model =>
{
model.Id(c => c.ProductID);
})
.Create("Create", "Home")
.Read("GetSub","Home")
.Update("Edit", "Home")
.Destroy("Delete", "Home")
.PageSize(10)
)
.HtmlAttributes(new { style= "width: 800px" })
)
What's a solution could be solve in this case? Thank you for your reply, have a great day!

Resources