I am using kendo grid in my MVC project. The problem is that the error message cannot be displayed on the watch page. When I track JSON data using the Google developer tools, I can view the error data correctly:
{"Data":null,"Total":0,"AggregateResults":null,"Errors":["There is record(s) with same name.Please review your new records."]}
The error message is passed to the result parameter on the controller.
controller
catch (Exception exp)
{
var result = exp.ToDataSourceResult(request);
return Json(result, JsonRequestBehavior.AllowGet);
}
This is the kendo grid code on the watch page:
<!-- Grid -->
@(Html.Kendo().Grid<AIS.UI.WebService.Proxy.DSrvAllService.AMBULANCEDEFINITIONS>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(product => product.DESCRIPTION).Title("<strong>Ambulance Description</strong>").Width("20%");
columns.Bound(product => product.CODE).Title("<strong>Ambulance Description</strong>").Width("20%");
columns.Command(commands =>
{
commands.Destroy().HtmlAttributes(new { id = "buttondelete" ,style="display:none" });
}).Title("Operations").Width("10%");
})
.ToolBar(toolbar =>
{
toolbar.Create().HtmlAttributes(new { id="addbutton",style = "font-weight:bold;color:blue" }).Text("Add Records");
toolbar.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Pageable(pager => pager
.PageSizes(true)
.Input(true)
.Refresh(true)
)
.Sortable()
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(true)
.Events(events => events.Error("onError"))
.Model(model =>
{
model.Id(product => product.ID);
model.Field(product => product.ID).Editable(false).DefaultValue(Guid.Empty);
model.Field(p => p.DESCRIPTION).Editable(false);
model.Field(product => product.CODE).Editable(false);
})
.Events(events => events.Error("onError"))
.Create(create => create.Action("AmbulanceCreate", "Administrator"))
.Read(read => read.Action("AmbulanceRead", "Administrator"))
.Update(update => update.Action("AmbulanceUpdate", "Administrator"))
.Destroy(destroy => destroy.Action("AmbulanceDelete", "Administrator"))
)
)
Js
function onError(e, status) {
if (e.errors) {
var message = "The following errors have occurred:\n";
$.each(e.errors, function (key, value) {
if (value.errors) {
message += value.errors.join("\n");
}
});
alert(message);
}
}
----- SOLVED -----
solved. To send an error message from the controller for viewing, you must use ModelState.
if(condition)
{
throw new Exception("Error msg ");
}
catch (Exception exp)
{
ModelState.AddModelError("UpdateAmbulance", exp.Message);
var result = ModelState.ToDataSourceResult();
return Json(result, JsonRequestBehavior.AllowGet);
}
And I added a line to the js code that rolls back the last record when an error message appears:
function onError(e, status) {
if (e.errors) {
var message = "\n";
$.each(e.errors, function (key, value) {
if (value.errors) {
message += value.errors.join("\n");
}
});
alert(message);
$("#grid").data("kendoGrid").cancelChanges();
}
}