Kendo Grid - ASP.NET Core - error handler doesn't fire

2 Answers 1032 Views
Grid
Jim
Top achievements
Rank 1
Jim asked on 29 Mar 2022, 04:48 PM | edited on 29 Mar 2022, 05:37 PM

Hi,

I have a Kendo grid setup and I would like my controller's update action to assign a custom error to the ModelState and have that picked up on the client side. This is not an actual error, but more of a flag I can catch on the client side to initiate a redirect to another page (similar to the concept posted here: Redirect to another page after update in Kendo grid with inline edit in UI for ASP.NET MVC | Telerik Forums

My issue is that I cannot get the error handler to fire on the client side. Here is my controller action (I've reduced it down to just the error handling for simplicity):

[HttpPost]
 public JsonResult Status_Update([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")] IEnumerable<StatusViewModel> changedEntries)
 {
     ModelState.AddModelError("UserRedirect", "UserRedirect needed");
     var result = ModelState.ToDataSourceResult();
     return Json(result);
 }

 

Here is my grid setup:


@(Html.Kendo().Grid(Model)
            .Name("status-grid")
            .Columns(c =>
            {
              // snip column setup
            })
            .ToolBar(toolbar =>
            {
                toolbar.Custom().Text("Save changes and submit").HtmlAttributes(new { id = "saveButton" });
            })
            .Editable(editable => editable.Mode(GridEditMode.InCell))
            .Scrollable(s => s.Height(850))
            .Navigatable()
            .Events(events =>
            {
                events.Edit("onEdit");
                events.Navigate("onNavigate");
            })
            .DataSource(dataSource => dataSource
                .Ajax()
                .Batch(true)
                .ServerOperation(false)
                .Events(events => events.Error("onError"))
                .Model(model =>
                {
                    // snip model fields
                })
                .Update("Status_Update", "Status"))
            )

 

Finally, here is my error handler function:


<script type="text/javascript">
    function onError(e) {
        alert("Error handler fired");
    }
</script>

 

I feel like this is a pretty vanilla setup, so I'm not sure why it isn't working. I've tried quite a few variations and the error handler never executes. I have no errors in the console. Here is the JSON that is being received on the client side. Can anyone see anything I am doing wrong, or tell me a better way to redirect the user to another page after the AJAX Update action finishes running? Thanks!!


{errors: {ValidationRedirect: {errors: ["ValidationRedirect needed"]}}}
errors: {ValidationRedirect: {errors: ["ValidationRedirect needed"]}}
ValidationRedirect: {errors: ["ValidationRedirect needed"]}
errors: ["ValidationRedirect needed"]
0: "ValidationRedirect needed"

2 Answers, 1 is accepted

Sort by
0
Stoyan
Telerik team
answered on 01 Apr 2022, 03:33 PM | edited on 04 Apr 2023, 09:42 PM

Hi Jim,

The correct way to add an error to the DataSourceResult is:

...
var result = changedEntries.ToDataSourceResult(request, ModelState);
return Json(result);
That being said there are some alternatives to the approach suggested in the forum thread.

 

  1. If you redirect to another page and you don't need to immediately update the Grid, you can skip returning Json and instead redirect to the desired page. As long as the updated data is persisted, the next read of the Grid will show the changes.
  2. If you redirect to a static url that remains the same, you can do that in the RequestEnd Event handler of the DataSource
.DataSource(dataSource => dataSource
                .Ajax()
                ...
                .Events(events => events.Error("onError").RequestEnd("onEnd"))
            )
function onEnd(e){
    if(e.type=="update"){
          document.location.href="/test"
    }
}

I hope the information above is useful.

Regards,
Stoyan
Progress Telerik

Love the Telerik and Kendo UI products and believe more people should try them? Invite a fellow developer to become a Progress customer and each of you can get a $50 Amazon gift voucher.

0
Jeremy
Top achievements
Rank 1
Iron
answered on 05 Aug 2022, 05:40 PM

Hi Jim,

I ran into the exact same situation.  In my case, the issue was that the default Json serialization for .net core was changing the case on the return properties.

The following fails to trigger the error event on the client side:

        [HttpPost]
        public IActionResult Index([DataSourceRequest] DataSourceRequest request, EditUserVm model)
        {
            ModelState.AddModelError("", "Update Failed");
            return Json(new List<EditUserVm> { model }.ToDataSourceResult(request, ModelState));
        }

The following successfully triggers the error event on the client side:

        [HttpPost]
        public IActionResult Index([DataSourceRequest] DataSourceRequest request, EditUserVm model)
        {
            ModelState.AddModelError("", "Update Failed");
            return Json(new List<EditUserVm> { model }.ToDataSourceResult(request, ModelState), new JsonSerializerOptions { PropertyNamingPolicy = null });
        }

Hope it works for you!

Jeremy

 

Stoyan
Telerik team
commented on 09 Aug 2022, 10:04 AM

Hi Jeremy,

Thank you for sharing your approach.

I just wanted to mention there is a more general approach to configure the Json Serialization if you need it.

To use it add the AddJsonOption service to the ConfigureServices method of the project:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services
            .AddControllersWithViews()
            .AddJsonOptions(options => 
                options.JsonSerializerOptions.PropertyNamingPolicy = null);

    // Add the Kendo UI services to the services container.
    services.AddKendo();
}

For more information refer to the Json Serialization article.

Regards,
Stoyan

 

Jeremy
Top achievements
Rank 1
Iron
commented on 09 Aug 2022, 08:40 PM

Thanks, Stoyan.  Setting the JsonOptions globally works perfectly.  
Taylor
Top achievements
Rank 1
commented on 04 Apr 2023, 06:56 PM

Almost a year later, but I had the same problem, and setting JsonOptions also worked for me.  Thanks!
Tags
Grid
Asked by
Jim
Top achievements
Rank 1
Answers by
Stoyan
Telerik team
Jeremy
Top achievements
Rank 1
Iron
Share this question
or