grid kendo ui edit create delete - user-interface

I have page mvc cshtml
it contains an begin beginform:
#using (Html.BeginForm("ValiderLeChangement", "FichePersonnel", FormMethod.Post , new { id = "FormValider" } ))
{
}
inside this form i have put grid kendo ui in this kendo grid i want to use
create add and delete like example in Kendo UI DEMO ( http://demos.kendoui.com/web/grid/editing-inline.html)
i ve probleme with the action of create or delete or edit don't fire on server
my code is :
#(Html.Kendo().Grid(Model.ListeContact)
.Name("Grid")
.Editable(editable => editable.Mode(GridEditMode.InLine))
.ToolBar(toolbar => toolbar.Create())
.Columns(columns =>
{
columns.Bound(p => p.Nom).Title("Nom").Width(20);
columns.Bound(p => p.Prenom).Title("Prenom").Width(20);
//columns.Bound(p => p.Lien.Libelle).Title("Lien").Width(20).ClientTemplate(????? );
columns.Bound(p => p.Lien.Libelle).Title("Lien").Width(20);
columns.Bound(p => p.Tel).Title("Telephone").Width(20);
columns.Command(command => { command.Edit(); }).Width(30);
columns.Command(command => { command.Destroy(); }).Width(30);
///////// columns.Bound(p => p.IdContact).ClientTemplate("#= Delete(data) #").Title("Supprimer").Width(5);
})
.Sortable()
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(true)
.Events(events => events.Error("error_handler"))
.Read(Read => Read.Action("ListeContact_Read", "FichePersonnel"))
.Model(model => model.Id(p => p.IdContact))
.Create(create => create.Action("EditingInline_Create", "FichePersonnel"))
.Update(update => update.Action("EditingInline_Update", "FichePersonnel"))
.Destroy(delete => delete.Action("EditingInline_Destroy", "FichePersonnel"))
)
)

How have you implemented your controller action method? Does it handles the request and return properly? It should be something like this:
public ActionResult EditingInline_Create([DataSourceRequest] DataSourceRequest request, ProductViewModel product)
{
if (product != null && ModelState.IsValid)
{
SessionProductRepository.Insert(product);
}
return Json(new [] { product }.ToDataSourceResult(request, ModelState));
}
Note the first argument DataSourceRequest and teh return type Json. Maybe that's what you're missing. Also I noticed that you're indicating ServerOperation(true). As far as I understand, you should not need that if you are using AJAX Binding as you are.
EDIT:
And so for the controller code, something like this:
public partial class TextosController : EditorImageBrowserController
{
public ActionResult ReadTextos([DataSourceRequest]DataSourceRequest request)
{
CostSimulatorModel modelo = new CostSimulatorModel(new Uri(#"http://localhost:53212/CostSimulatorModelService.svc/"));
IQueryable<Texto> textos = modelo.Textos;
DataSourceResult resultado = textos.ToDataSourceResult(request);
ViewData["Textos"] = textos;
return Json(resultado, JsonRequestBehavior.AllowGet);
}
public ActionResult CreateTexto([DataSourceRequest]DataSourceRequest request, Texto texto)
{
if (ModelState.IsValid)
{
CostSimulatorModel modelo = new CostSimulatorModel(new Uri(#"http://localhost:53212/CostSimulatorModelService.svc/"));
// Create a new Product entity and set its properties from the posted ProductViewModel
Texto entity = new Texto
{
TextoID = texto.TextoID,
Titulo = texto.Titulo,
Corpo = texto.Corpo,
IsPrivado = texto.IsPrivado,
TipoTextoID = texto.TiposTexto != null ? texto.TiposTexto.TipoTextoID : texto.TipoTextoID,
TiposTexto = texto.TiposTexto
};
modelo.AddToTextos(entity);
// Insert the entity in the database
modelo.SaveChanges();
// Get the ProductID generated by the database
texto.TextoID = entity.TextoID;
return Json(new[] { entity }.ToDataSourceResult(request, ModelState));
}
// Return the inserted product. The grid needs the generated ProductID. Also return any validation errors.
return Json(new[] { texto }.ToDataSourceResult(request, ModelState));
}
public ActionResult UpdateTexto([DataSourceRequest]DataSourceRequest request, Texto texto)
{
if (ModelState.IsValid)
{
CostSimulatorModel modelo = new CostSimulatorModel(new Uri(#"http://localhost:53212/CostSimulatorModelService.svc/"));
// Create a new Product entity and set its properties from the posted ProductViewModel
var entity = new Texto
{
TextoID = texto.TextoID,
Titulo = texto.Titulo,
Corpo = texto.Corpo,
IsPrivado = texto.IsPrivado,
TipoTextoID = texto.TiposTexto != null ? texto.TiposTexto.TipoTextoID : texto.TipoTextoID,
TiposTexto = texto.TiposTexto
};
// Attach the entity
modelo.AttachTo("Textos", entity);
modelo.UpdateObject(entity);
// Update the entity in the database
modelo.SaveChanges();
return Json(new[] { entity }.ToDataSourceResult(request, ModelState));
}
// Return the updated product. Also return any validation errors.
return Json(new[] { texto }.ToDataSourceResult(request, ModelState));
}
public ActionResult DestroyTexto([DataSourceRequest]DataSourceRequest request, Texto texto)
{
if (ModelState.IsValid)
{
CostSimulatorModel modelo = new CostSimulatorModel(new Uri(#"http://localhost:53212/CostSimulatorModelService.svc/"));
// Create a new Product entity and set its properties from the posted ProductViewModel
var entity = new Texto
{
TextoID = texto.TextoID
};
// Attach the entity
modelo.AttachTo("Textos", entity);
// Delete the entity
modelo.DeleteObject(entity);
// Delete the entity in the database
modelo.SaveChanges();
return Json(new[] { entity }.ToDataSourceResult(request, ModelState));
}
// Return the removed product. Also return any validation errors.
return Json(new[] { texto }.ToDataSourceResult(request, ModelState));
}
}

Related

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:

KendoUI (Telerik 2018) - TreeList is not showing newly created record till manual refresh

I am able to create new record in TreeList for MVC. But it shows newly created record only after refreshing the page. Edit and Delete works fine.
Razor Code
#(Html.Kendo().TreeList<KendoEx.Web.Models.Level>()
.Name("lvlTreeList")
.Toolbar(toolbar =>
{
toolbar.Create();
})
.Columns(columns =>
{
columns.Add().Field(e => e.LvlName).Title("Name").Width(120);
columns.Add().Field(e => e.LvlType).Title("Type").Width(80);
columns.Add().Field(e => e.Rating1).Title("Rating 1").Filterable(false).Width(100);
columns.Add().Field(e => e.Rating2).Title("Rating 2").Filterable(false).Width(100);
columns.Add().Command(c =>
{
c.CreateChild().Text("Add child");
c.Edit();
c.Destroy();
}).Width(180);
})
.Editable(e => e.Mode("inline"))
.DataSource(dataSource => dataSource
.Read(read => read.Action("GetLevel", "Level"))
.Create(create => create.Action("Save", "Level"))
.Update(update => update.Action("Save", "Level"))
.Destroy(delete => delete.Action("Remove", "Level"))
.Model(m =>
{
m.Id(f => f.Id);
m.ParentId(f => f.ParentLvl).DefaultValue(0);
m.Expanded(true);
m.Field(f => f.LvlName);
m.Field(f => f.LvlType);
m.Field(f => f.Rating1);
m.Field(f => f.Rating1);
}))
.Height(550))
Controller Methods
public JsonResult GetLevel([DataSourceRequest] DataSourceRequest request)
{
var lvlList = LoadLevels().ToTreeDataSourceResult(request);
return Json(lvlList, JsonRequestBehavior.AllowGet);
}
private IEnumerable<Level> LoadLevels()
{
IEnumerable<Level> lvlList = Enumerable.Empty<Level>(); ;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["WebApiExUrl"]);
var responseTask = client.GetAsync("getlevel");
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<FormattedResult<Level>>();
readTask.Wait();
if (string.IsNullOrEmpty(readTask.Result.Error))
{
IEnumerable<Level> tempList = readTask.Result.Data;
lvlList = tempList.Select(m => new Level
{
Id = m.Id,
LvlName = m.LvlName,
LvlType = m.LvlType,
ParentLvl = m.ParentLvl,
Rating1 = m.Rating1,
Rating2 = m.Rating2,
hasChildren = tempList.Where(s => s.ParentLvl == m.Id).Count() > 0
});
}
}
}
return lvlList;
}
public JsonResult Save([DataSourceRequest] DataSourceRequest request, Level level)
{
if (level != null && ModelState.IsValid)
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["KpiApiUrl"]);
var postTask = client.PostAsJsonAsync("savelevel", level);
postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsStringAsync();
readTask.Wait();
}
}
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, "Unexpected error");
}
}
return Json(new[] { level }.ToTreeDataSourceResult(request, ModelState));
}
Model
public class Level
{
public int Id { get; set; }
public string LvlName { get; set; }
public string LvlType { get; set; }
public int? ParentLvl { get; set; }
[RegularExpression(#"^(\d{1,2}(\.\d{0,2})?)?(<|<=|>|>=)(\d{1,3}(\.\d{0,2})?)$", ErrorMessage = "Invalid")]
public string Rating1 { get; set; }
[RegularExpression(#"^(\d{1,2}(\.\d{0,2})?)?(<|<=|>|>=)(\d{1,3}(\.\d{0,2})?)$")]
public string Rating2 { get; set; }
}
If the 'Save' method returns
return Json(LoadLevels().ToDataSourceResult(request, ModelState), JsonRequestBehavior.AllowGet);
instead of
return Json(new[] { level }.ToTreeDataSourceResult(request, ModelState));
the TreeList shows duplicate records
The 'Save' event of TreeList also behaves in the same way.
function onSave() {
$("#lvlTreeList").data("kendoTreeList").dataSource.read();
}
Version Info: Telerik 2018.1.221.545, MVC 5.2, .NET 4.6
Please advise on this. Thanks.
Demo Link: https://demos.telerik.com/aspnet-mvc/treelist/editing
Calling read() in Sync event of DataSource, refreshes the TreeList and displays newly created level.
Razor Code
#(Html.Kendo().TreeList<..>()
.Name("lvlTreeList")
/*..*/
.DataSource(dataSource => dataSource
.Events(e => e.Sync("lvlTreeList_Sync"))
/*...*/
))
Javascript
<script>
function lvlTreeList_Sync() {
this.read();
}
</script>
Refer: https://www.telerik.com/forums/refresh-after-upda

Kendo Grid dynamic columns and update the batch Values

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

Bind local data to kendo grid and make it sortable

I am trying to setup kendo mvc ui grid using local data and make it sortable as in this demo Binding to local data.
However grid doesn't show data and if I hook up the onDataBound event, data inside there is undefined.
If I comment out DataSource setup on view, data gets populated at first, but disappears after sorting performed on any column.
I am using Kendo UI version: "2013.3.1119", asp.net mvc 4.
Please advice.
Thanks.
view
#model TestViewModel
#(Html.Kendo().Grid(Model.TestList)
.Name("grid2")
.Columns(columns =>
{
columns.Bound( p => p.Id ).Title( "ID" );
columns.Bound( p => p.Name ).Title("Product Name");
})
.Pageable()
.Sortable()
.Scrollable(scr=>scr.Height(430))
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.ServerOperation(false))
)
controller and model
public class TestController : Controller
{
//
// GET: /Test/
public ActionResult Index()
{
var mdl = new TestViewModel();
mdl.TestList = Test().ToList();
return View(mdl);
}
public IEnumerable<TestMe> Test()
{
var lst = new List<TestMe>();
for( int i = 0; i < 5; i++ )
{
lst.Add( new TestMe
{
Id = i,
Name = i.ToString(),
} );
}
return lst;
}
}
public class TestViewModel
{
public List<TestMe> TestList { get; set; }
public TestViewModel()
{
TestList = new List<TestMe>();
}
}
public class TestMe
{
public int Id { get; set; }
public string Name { get; set; }
}

Paging not working in my Telerik Grid

I'm working on a grid currently that has an issue with paging. The grid fills up to the point it has 15 items within it. That is the Page Size max, however, pages are not added beyond that. I'm not entirely sure why it does not add pages. Below is my code.
View
var gridPageSize = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().GridPageSize;
<table class="adminContent">
<tr>
<td>
#(Html.Telerik().Grid<CategoryModel.CategoryUnitsModel>()
.Name("categoryunits-grid")
.DataKeys(keys =>
{
keys.Add(x => x.Id);
keys.Add(x => x.CategoryId);
keys.Add(x => x.UnitId);
})
.DataBinding(dataBinding =>
{
dataBinding.Ajax()
.Select("CategoryUnitsList", "Category", new { categoryId = Model.Id })
.Insert("CategoryUnitsInsert", "Category", new { categoryId = Model.Id })
.Update("CategoryUnitsInsert", "Category", new { categoryId = Model.Id })
.Delete("CategoryUnitsDelete", "Category", new { categoryId = Model.Id });
})
.Columns(columns =>
{
columns.Bound(x => x.UnitId)
.Visible(false);
columns.Bound(x => x.UnitText);
columns.Command(commands =>
{
commands.Edit();
commands.Delete();
})
.Width(100);
})
.ToolBar(commands => commands.Insert())
.Pageable(settings => settings.PageSize(gridPageSize).Position(GridPagerPosition.Both))
.ClientEvents(events => events.OnRowDataBound("onRowDataBound"))
.ClientEvents(events => events.OnEdit("onEdit"))
.EnableCustomBinding(true))
<script type="text/javascript">
function onRowDataBound(e) {
$(e.row).find('a.t-grid-edit').remove(); //remove Delete button
}
function onEdit(e) {
$.getJSON('#Url.Action("LoadAvailableUnits", "Category")', { categoryId: $("#Id").val() }, function (data) {
var ddl = $("#UnitText").data("tDropDownList");
if (data.length > 0) {
ddl.dataBind(data);
ddl.reload();
}
else {
$('a[class="t-button t-grid-cancel"]').click();
alert("There are no Units left to select from");
}
});
}
</script>
</td>
</tr>
</table>
EditorTemplates\CategoryUnit
#using Telerik.Web.Mvc.UI;
#Html.Telerik().DropDownList().Name("UnitText")
Model (CategoryModel.CategoryUnitsModel)
public partial class CategoryUnitsModel : BaseNopEntityModel
{
public int CategoryId { get; set; }
public int UnitId { get; set; }
[NopResourceDisplayName("Admin.Catalog.Categories.Units.Fields.UnitText")]
[UIHint("CategoryUnit")]
public string UnitText { get; set; }
}
Controller
[HttpPost, GridAction(EnableCustomBinding = true)]
public ActionResult CategoryUnitsList(GridCommand command, int categoryId)
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
return AccessDeniedView();
var categoryUnits = _unitsService.GetCategoryUnits(categoryId, command.Page - 1, command.PageSize);
var categoryUnitsModel = PrepareCategoryUnitsModel(categoryUnits);
var model = new GridModel<CategoryModel.CategoryUnitsModel>
{
Data = categoryUnitsModel,
Total = categoryUnitsModel.Count
};
return new JsonResult
{
Data = model
};
}
public JsonResult LoadAvailableUnits(int categoryId)
{
var categoryUnits = _unitsService.GetAvailableUnits(categoryId);
var categoryUnitsModel = PrepareAvailableUnitsInModel(categoryUnits);
var returnData = new SelectList(categoryUnitsModel, "UnitId", "UnitText");
return Json(returnData, JsonRequestBehavior.AllowGet);
}
[GridAction(EnableCustomBinding = true)]
public ActionResult CategoryUnitsInsert(GridCommand command, CategoryModel.CategoryUnitsModel model)
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
return AccessDeniedView();
var searchForEntry = _unitsService.GetCategoryUnitByCategoryIdAndUnitId(model.CategoryId, Int32.Parse(model.UnitText));
if (searchForEntry != null)
{
return CategoryUnitsList(command, model.CategoryId);
}
var categoryUnit = new CategoryUnits
{
UnitId = Int32.Parse(model.UnitText),
CategoryId = model.CategoryId
};
_unitsService.InsertCategoryUnit(categoryUnit);
return CategoryUnitsList(command, model.CategoryId);
}
[GridAction(EnableCustomBinding = true)]
public ActionResult CategoryUnitsDelete(GridCommand command, CategoryModel.CategoryUnitsModel model, int id)
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
return AccessDeniedView();
var categoryId = model.CategoryId;
_unitsService.DeleteCategoryUnit(model.CategoryId, id);
return CategoryUnitsList(command, categoryId);
}
Any help would be much appreciated. Thanks all.
Kindest Regards,
Chad Johnson
Nevermind, I figured out the issue. In my Controller, when I set the Total when binding the grid, I was using the count of the data that had been bound to the Model instead of the total count that my Entity brought back.

Resources