Kendo UI ASP.NET MVC Kendo Grid Edit Popup Globalization Validation Issue - asp.net-mvc

i have a Kendo grid that uses an edit Popup. The culture in the client is de-DE, when an user tries to edit a decimal number i.e. 8,5 Kendo sends a null to the server for that value and returns validation message "The value 8.5 is not valid for 'PropertyName'". Any help will be greatly appreciated.
#{
var culture = System.Globalization.CultureInfo.CurrentCulture.ToString();
}
<script src="#Url.Content("~/Scripts/Kendo/cultures/kendo.culture." + culture + ".min.js")"></script>
jQuery.extend(jQuery.validator.methods, {
date: function (value, element) {
return this.optional(element) || kendo.parseDate(value) != null;
},
number: function (value, element) {
return this.optional(element) || kendo.parseFloat(value) != null;
}
});
<script type="text/javascript">
kendo.culture("#culture");
</script>
#(Html.Kendo().Grid<SalesToolkit.ViewModels.AdminEquipDimViewModel.Equipment>()
.Name("grdEquipDim")
.Columns(columns =>
{
columns.Bound(dim => dim.EquipmentID).Width(50).Title("ID").Hidden(true);
columns.Bound(dim => dim.EquipmentName).Width(140).Title("Equipment Name");
columns.ForeignKey(dim => dim.EquipmentTypeID, (System.Collections.IEnumerable)ViewData["EquipTypes"], "EquipmentTypeID", "EquipmentName").Width(60).Title("Type");
columns.Bound(dim => dim.Metric).Width(55);
columns.Bound(dim => dim.ModelVerified).Width(65);
columns.Bound(dim => dim.LastModifiedBy).Width(130);
columns.Bound(dim => dim.TimeStamp).Format("{0:MM/dd/yyyy hh:mm:ss}").Width(120);
columns.Command(command => { command.Edit(); command.Destroy(); }).Width(160);
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.PopUp))
.Scrollable()
.HtmlAttributes(new { #class = "dimGrid" })
.Sortable()
.Pageable()
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Field(dim => dim.EquipmentID).Editable(false);
model.Field(dim => dim.TimeStamp).Editable(false);
model.Field(dim => dim.LastModifiedBy).Editable(false);
})
.Events(events => events.Error("error"))
.Model(model => model.Id(dim => dim.EquipmentID))
.Create(update => update.Action("EquipDim_Create", "AdminEquipDim", new { mID = Model.ManufacturerID }))
.Read(read => read.Action("EquipDim_Read", "AdminEquipDim", new { mID = Model.ManufacturerID }))
.Update(update => update.Action("EquipDim_Update", "AdminEquipDim"))
.Destroy(update => update.Action("EquipDim_Delete", "AdminEquipDim"))
)
)
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EquipDim_Update([DataSourceRequest] DataSourceRequest request, AdminEquipDimViewModel.Equipment equipMfg)
{
if (equipMfg != null && ModelState.IsValid)
{
AdminEquipDim oEquipMfg = new AdminEquipDim();
oEquipMfg.UpdateEquipDim(equipMfg);
}
return Json(ModelState.ToDataSourceResult());
}

Related

Kendo.Grid Delete Acton does not invoke the Controller's method even though I'm doing the same as in telerik example

I have the following Kendo().Grid():
#(Html.Kendo().Grid<TicketReportPropertyEntity>()
.Name("TicketReportPropertyGrid")
.Columns(columns =>
{
columns.Bound(c => c.ID).Hidden();
columns.Bound(c => c.PropertyName).Title("Property Name").EditorTemplateName("_PropertyNameEditor").Width(900);
columns.Bound(c => c.Amount).Title("Amount").Format("{0:C}").Width(90);
columns.Command(command => command.Destroy()).Width(150);
})
.Events(events => events.DataBound("Databound").SaveChanges("SaveGrid").Edit("Edit"))
.ToolBar(toolbar =>
{
toolbar.Create();
toolbar.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Navigatable()
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(false)
//.Events(events => events.Error("error_handler"))
.Model(model =>
{
model.Id(c => c.ID);
model.Field(c => c.PropertyName);
model.Field(c => c.Amount);
})
.Create(create => create.Action("AddTicketReportProperty", "TicketReportProperty").Data("GetData"))
.Read(read => read.Action("GetData", "TicketReportProperty", Model))
.Update(update => update.Action("UpdateTicketReportProperty", "TicketReportProperty"))
.Destroy(delete => delete.Action("DeleteTicketReportProperty", "TicketReportProperty"))
)
)
And my controller's method:
[HttpPost]
public ActionResult DeleteTicketReportProperty([DataSourceRequest] DataSourceRequest request, TicketReportPropertyModel model)
{
var result = new TicketReportPropertyModel().DeleteTicketReportProperty(model.ID);
return Json(new[] { model }.ToDataSourceResult(request, ModelState));
}
Here is a "SaveGrid" function:
function SaveGrid(e) {
console.log("save")
var rowsCount = e.sender.dataSource.data().length;
var totalSum = 0;
if (rowsCount > 0) {
for (var i = 0; i < rowsCount; i++) {
totalSum += e.sender.dataSource.data()[i].Amount;
}
}
var ticketAmount = $('#Ticket_Amount').val();
console.log(ticketAmount);
if (totalSum != ticketAmount) {
console.log("failed");
//show the popup
e.preventDefault();
}
}
It should add, update and delete records. Now, I'm working on deleting the record. But the event does not call the controller.
I'm following telerik example here
What am I missing?
I believe you are not following exactly the example from telerik. When you create the Grid you're using an Entity TicketReportPropertyEntity, but in the Controller you are receiving a Model TicketReportPropertyModel.
Make sure you create your Grid using the Model, not the Entity, as the example you're following.
#(Html.Kendo().Grid<TicketReportPropertyModel>()

Kendo Grid edit command not reaching controller

Can someone please help with my question:
The edit command in kendo grid isn't reaching my controller.
Am I missing something?
#(Html.Kendo().Grid<WEEKLY_ORDERS_LINES>()
.Name("orderDetails_edit" + Model.OrderID)
.Columns(columns =>
{
columns.Bound(e => e.ID).Hidden(true);
columns.Bound(e => e.INGRED_NAME).Title("Ingredient Name").Width(120).HeaderHtmlAttributes(new { style = "text-align: center;" }).HtmlAttributes(new { style = "text-align: center;" });
columns.Command(command => { command.Edit(); }).Width(60);
})
.Editable(e => e.Mode(GridEditMode.InLine))
.DataSource(dataSource => dataSource
.Ajax()
.Sort(sort => sort.Add("INGRED_NAME").Ascending())
.Model(model =>
{
model.Id(p => p.ID);
model.Field(p => p.ID).DefaultValue(new Guid());
model.Field(f => f.INGRED_NAME).Editable(true);
})
.Update(update => update.Action("Update", "Food"))
.Read(read => read.Action("Read", "Food").Data("additionalInfo"))
)
.Events(events => events.Cancel("refreshView"))
)
And my controller is like this:
public ActionResult Update([DataSourceRequest] DataSourceRequest request, WEEKLY_ORDERS_LINES model)
{
if (model != null && ModelState.IsValid)
{
WEEKLY_FOOD dbFood = _db.WEEKLY_FOOD.Find(model.ID);
dbFood.INGRED_NAME = model.INGRED_NAME;
_db.SaveChanges();
}
ActionResult a = Json(new[] { model }.ToDataSourceResult(request, ModelState));
return a;
}
I'm a colleague of Rute.
The problem that was ocurring was that the kendo Update was calling other controller and not the right one. This was happening because all the results of the data that were being rendered didn't have an unique identifier.
This unique identifier is now assign to the model.Id and the problem is solved. I understood this after seeing this link http://www.telerik.com/forums/wrong-methods-are-fired.
Thanks for the help.

How to only update a row in Telerik MVC grid without refreshing the grid data?

From the samples and documentation, it looks like if I want to update one row (or do a batch update) in a Telerik grid, I also need to refresh the data in the entire grid.
Is there a way to just update that one row on the client and not return all the grid data every time I want to do an update? It seems extremely wasteful to keep returning that much data every time.
Even if I do a batch update, why do I need to return all the new data?
Generally a database has many users, and your user interface may be accessed by multiple people. If the grid is going to update, then it will include any other changes that may have happened to the data since the grid originally loaded.
The grid allows you to limit the number of records that are shown at a time via the paging option. On our project we are loading the grid with AJAX, and using IQueryable's in the controller. When we call ToDataSourceResult(request) on the IQueryable, it only retrieves the data that is needed, and does not load the full table from the database.
On the Razor View:
#(Html.Kendo().Grid<WebApp.ViewModels.AccountViewModel>()
.Name("Accounts")
.Columns(columns =>
{
columns.Bound(c => c.AccountNumber);
columns.Bound(c => c.Name);
columns.Bound(c => c.Address1);
columns.Bound(c => c.Address2);
columns.Bound(c => c.City);
columns.Bound(c => c.State);
columns.Bound(c => c.Zip);
columns.Bound(c => c.PrimaryContact).Title("Contact");
})
.Filterable(filterable => filterable
.Extra(false)
.Operators(operators => operators
.ForString(str => str.Clear()
.Contains("Contains")
.DoesNotContain("Doesn't Contain")
)
)
)
.Groupable()
.Sortable()
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(new int[] { 5, 10, 20, 50, 100, 500 })
.ButtonCount(5)
)
.DataSource(dataSource => dataSource
.Ajax()
.Sort(sort => sort.Add("Name").Ascending())
.PageSize(20)
.Read(read => read.Action("Account_Read", "Account"))
)
)
Then in the controller:
public ActionResult Account_Read([DataSourceRequest] DataSourceRequest request)
{
var jsonlist = GetAccounts()
.Select(sa => new AccountViewModel
{
ID = sa.ID,
AccountNumber = sa.AccountNumber,
Name = sa.Name,
Address1 = sa.Address1,
Address2 = sa.Address2,
City = sa.City,
State = sa.State,
Zip = sa.Zip,
PrimaryContact = sa.User.FirstName + " " + sa.User.LastName
}
).ToDataSourceResult(request);
return Json(jsonlist);
}
UPDATE
We have an inline edit form on one of our Kendo grids. It took us a bit to get it how we watned. In the Razor View:
#(Html.Kendo().Grid<DataViewModel>()
.Name("Data")
.Columns(columns =>
{
columns.Bound(c => c.FieldName)
.EditorTemplateName("DataFieldName")
.Title("Item Name")
.Width(200);
columns.Bound(c => c.TextValue)
.Title("Text");
columns.Command(command => { command.Edit(); command.Destroy(); })
.Title("Actions")
.Width(172);
})
.Filterable()
.Sortable()
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(new int[] { 5, 10, 20, 50, 100 })
.ButtonCount(5)
)
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.InLine))
.DataSource(dataSource => dataSource
.Ajax()
.Sort(sort => sort.Add("CreatedDate").Descending())
.PageSize(20)
.Events(events => events.Error("error_handler"))
.Model(model =>
{
model.Id(pd => pd.ID);
model.Field(pd => pd.CreatedDate).Editable(false);
model.Field(pd => pd.ValuesID).DefaultValue(Model.Values.ID);
})
.Read(read => read.Action("Data_Read", "History", new { ValuesID = Model.Values.ID }))
.Create(update => update.Action("Data_Create", "History"))
.Update(update => update.Action("Data_Update", "History"))
.Destroy(update => update.Action("Data_Destroy", "History"))
)
)
<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);
}
}
</script>
In order to use the Kendo date time picker for the date option, we had to create a custom editor template. We created a new folder under Views >> Shared >> EditorTemplates. The file name is DataFieldName.cshtml:
#model WebApp.ViewModels.DataViewModel
#using WebApp.ViewModels
#(Html.Kendo().ComboBox()
.Name("FieldName")
.Placeholder("Select/Create Item Name")
.DataTextField("Name")
.DataValueField("Name")
.Filter(FilterType.Contains)
.DataSource(source => source
.Read(read => read.Action("GetFieldNames", "History"))
)
)
Then the controller has all of the action results for the AJAX calls:
[HttpPost]
public ActionResult Data_Create(DataViewModel DataIn)
{
var Data = new Data();
Data.ValuesID = DataIn.ValuesID;
Data.FieldName = DataIn.FieldName;
Data.TextValue = DataIn.TextValue;
if (DataIn.TimeValue != null) Data.TimeValue = DataIn.TimeValue;
if (ModelState.IsValid)
{
db.Datas.Add(Data);
db.SaveChanges();
}
return RedirectToAction("EditValue", new
{
ValueID = DataIn.ValuesID,
tankID = db.Values.FirstOrDefault(pv => pv.ID == DataIn.ValuesID).TankID
});
}
[HttpPost]
public ActionResult Data_Update(DataViewModel DataIn)
{
var Data = db.Datas.Find(DataIn.ID);
Data.FieldName = DataIn.FieldName;
Data.TextValue = DataIn.TextValue;
if (DataIn.TimeValue != null) Data.TimeValue = DataIn.TimeValue;
if (ModelState.IsValid)
{
db.Entry(Data).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("EditValue", new
{
ValueID = DataIn.ValuesID,
tkID = db.Values.FirstOrDefault(pv => pv.ID == DataIn.ValuesID).tkID
});
}
[HttpPost]
public ActionResult Data_Destroy(DataViewModel DataIn)
{
var Data = db.Datas.Find(DataIn.ID);
db.Datas.Remove(Data);
db.SaveChanges();
return RedirectToAction("EditValue", new
{
ValueID = DataIn.ValuesID,
tkID = db.Values.FirstOrDefault(pv => pv.ID == DataIn.ValuesID).tkID
});
}
public ActionResult GetFieldNames()
{
var jsonList = db.Datas
.Select(pd => new
{
Name = pd.FieldName
})
.Distinct()
.OrderBy(pd => pd.Name)
.ToList();
return Json(jsonList, JsonRequestBehavior.AllowGet);
}

How can I store value inside Telerik Grid in ASP.Net MVC?

I am using Telerik grid in ASP.Net MVC, I want to store "Key" in ViewBag/Session and pass it to controller, "Key" is bound with column of telerik grid.
How can I achieve it?
#(Html.Telerik().Grid()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(e => e.Key).Width(140);
})
.ClientEvents(events => events.OnRowDataBound("OnRowDataBound"))
.DetailView(details => details.ClientTemplate(
Html.Telerik().TabStrip()
.Name("TabStrip_<#= Key #>")
.SelectedIndex(0)
.Items(items =>
{
items.Add().Text("Resolution").Content(
Html.Telerik().Grid<AnotherModel>()
.Name("Resolutions_<#= Key #>")
.Columns(columns =>
{
columns.Bound(f => f.CreatedDate).Width(140).Title("Date");
columns.Bound(f => f.Name).Title("Name");
})
.DataBinding(dataBinding => dataBinding.Ajax()
.Select("MyControllerAction2", "MyController",PASS_KEY_HERE_EACH_TIME))
//Here instead of PASS_KEY_HERE_EACH_TIME, I need 'Key' to pass here of FirstModel
.Pageable()
.Sortable()
.Filterable()
.Scrollable()
.ToHtmlString()
);
})
.ToHtmlString()
))
.DataBinding(dataBinding => dataBinding.Ajax().Select("MyControllerAction1", "MyController"))
.Pageable()
.Scrollable(scrolling => scrolling.Height(500))
.Sortable()
)
controller I want to call each time at binding
public ActionResult MyControllerAction2(string myKey)
{
var test = new List<Data>();
ProjectDetail projectDetail = new ProjectDetail();
test = projectDetail.GetData("KEY-123");
// Actually I want to use Key here which is passed in View at DataBinding(),
so that I can get all data I need
return View(new GridModel(test));
}
You can get this value in your OnRowDataBound(e) javascript function:
function onRowDatabound(e) {
var currentKey = e.dataItem.Key;
//send currentKey to controller
}
Update:
If you have master:detail, you can use next:
.DetailView(details => details.ClientTemplate("<div style='float:left' class='e-function-grid-detail' data-Key='<#= Key #>'>" +
Html.Telerik().TabStrip()
.Name("TabStrip_<#= Key #>")
.SelectedIndex(0)
.Items(items =>
{
items.Add().Text("Resolution").Content(
Html.Telerik().Grid<AnotherModel>()
.Name("Resolutions_<#= Key #>")
.Columns(columns =>
{
columns.Bound(f => f.CreatedDate).Width(140).Title("Date");
columns.Bound(f => f.Name).Title("Name");
})
.DataBinding(dataBinding => dataBinding.Ajax()
.Select("MyControllerAction2", "MyController"))
.Pageable()
.Sortable()
.Filterable()
.Scrollable()
.ClientEvents(ce => ce.OnDataBinding("function(e){ addKeyToRequest(this, e);}")
.ToHtmlString()
);
})
.ToHtmlString()
)) + "</div>"
and write js function
function addKeyToRequest(sender, e) {
var key= $(sender).closest('div.e-function-grid-detail').data("Key");
if (e.data == null || e.data == '') {
e.data = new Object();
}
e.data.Key = key;
}
This function is called before post for data to controller and add your key value to post.

Asp.Net MVC KendoUI grid

#(Html.Kendo().Grid<RTM.WEB.MVC.ViewModels.SortingViewModel.ProductViewModel>()
.Name("ProductsGrid").HtmlAttributes("height:430")
.Columns(columns =>
{
columns.Bound(p => p.IsSelected).Width(50).Title("");
columns.Bound(p => p.ProductName);
columns.Bound(p => p.Price).Format("{0:C}");
columns.Bound(p => p.GroupName);
// columns.Bound(p => p.MeasurementId);
// columns.Bound(p => p.BarcodeValue);
columns.Command(comand =>
{
comand.Custom("Edit").Click("ViewEdit");
comand.Destroy();
}).Title("Commands").Width(180);
})
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
//.Events(events=>events.Sync("addGroupData"))
.ServerOperation(true)
.Batch(true)
.Events(events =>
{
events.Error("errorHandler");
events.Sync("addDataToResponce");
})
.Model(model =>
{
model.Id(p => p.ProductId);
model.Field(p => p.ProductId).Editable(false);
})
// .Aggregates(aggregates =>
//{
// //aggregates.Add(p => p.ProductId);
// //aggregates.Add(p => p.ProductName);
// aggregates.Add(p => p.Price).Sum();
//})
.Group(groups => groups.Add(p => p.GroupName))
.Create(create => create.Action("Products_Create", "Sorting"))
.Read(read => read.Action("Products_Read", "Sorting"))
.Update(update => update.Action("Products_Update", "Sorting"))
.Destroy(destroy => destroy.Action("Products_Destroy", "Sorting"))
)
.ToolBar(toolbar =>
{
toolbar.Template(#<text>
<div >
<a class="k-button" onclick="AddProduct()">Add New Product</a>
#item.SaveButton()
<a class="k-button" onclick="NewGroup()">NewGroup</a>
<a class="k-button" onclick="UnGroup()">UnGroup</a>
<label>Show products by warehouse:</label>
#(Html.Kendo().DropDownList()
.Name("warehouses")
.OptionLabel("All")
.DataTextField("Name")
.DataValueField("WarehouseId")
.AutoBind(false)
// .Events(e => e.Change("warehousesChange"))
.DataSource(ds =>
{
ds.Read("Products_Warehouses", "Sorting");
})
)
</div>
</text>);
})
.Events(events =>
{
events.DataBound("dataBound");
})
.Pageable(page => page.PageSizes(true).Numeric(false).Refresh(true).Input(true))
//.Navigatable()
.Selectable()
.ColumnMenu()
.Filterable()
.Sortable()
.Scrollable()
.Editable(editable => editable.Mode(GridEditMode.InCell).DisplayDeleteConfirmation(false))
)
public JsonResult Products_Read([DataSourceRequest]DataSourceRequest request)
{
int allcount=0;
List<ProductModel> products= DataManager.ProductRepository.GetAllProducts(request.Page, request.PageSize,ref allcount);
List<ProductViewModel> productViewModels=new List<ProductViewModel>();
foreach (var product in products)
{
productViewModels.Add(ConvertProductViewModel(product));
}
if (request.Sorts.Count != 0)
{
string member = request.Sorts.First().Member;
string sorttype = request.Sorts.First().SortDirection.ToString();
switch (member)
{
case "IsSelected":
if (sorttype == "Ascending")
{
productViewModels = productViewModels.OrderBy(p => p.IsSelected).ToList();
}
if (sorttype == "Descending")
{
productViewModels = productViewModels.OrderByDescending(p => p.IsSelected).ToList();
}
break;
case "ProductName":
if (sorttype == "Ascending")
{
productViewModels = productViewModels.OrderBy(p => p.ProductName).ToList();
}
if (sorttype == "Descending")
{
productViewModels = productViewModels.OrderByDescending(p => p.ProductName).ToList();
}
break;
case "Price":
if (sorttype == "Ascending")
{
productViewModels = productViewModels.OrderBy(p => p.Price).ToList();
}
if (sorttype == "Descending")
{
productViewModels = productViewModels.OrderByDescending(p => p.Price).ToList();
}
break;
}
}
var result = new DataSourceResult()
{
Data = productViewModels,
Total = allcount,
AggregateResults = null,
Errors = null,
};
return Json(result, JsonRequestBehavior.AllowGet);
}
This is my code.When i return data from action server paging doesn't work.
I want do server paging kendo ui group grid, but response data type undefined.I need working example for group grid.It works in basic grid but don't work for group grid.
You should just need to update the controller method. As the sorting you are doing seems quite basic, you can use the supplied Kendo method ToDataSourceResult(DataSourceRequest request).
Add the following to your using section in the Controller:
using Kendo.Mvc.Extensions;
Then simply return:
return Json(productViewModels
.ToDataSourceResult(request, JsonRequestBehavior.AllowGet));
This should take care of any filtering, sorting, grouping, and paging for you.
You might also want to take a look at AutoMapper to more easily map objects from Product to ProductViewModel.

Resources