简体   繁体   中英

Validate data before inserting to Kendo Grid in ASP.NET MVC

When i add a new record or modify an existing row, I want to validate the new data in the Action Method. If the new value entered is not within a certain range 1 - 10 ( or if an existing value is modified to be outside the valid range), I don't want the insert/update to be successful.

I tried the following:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditingInline_Create([DataSourceRequest] DataSourceRequest request,   ProductViewModel product)
    {
         if (product != null && ModelState.IsValid)
         {    
              if (product.Price > 1 && product.Price < 10)
              {
                   SessionProductRepository.Insert(product); 
              }                               
         }

         return Json(new [] { product }.ToDataSourceResult(request, ModelState));
    }

However, when the method returns, a new row with the invalid Price data is added to the grid.

What am I missing? How can I fix the return statement to handle this case?

This Kendo UI Blog post might give you some ideas on how to handle this: http://www.kendoui.com/blogs/teamblog/posts/13-08-29/handling-server-side-validation-errors-in-your-kendo-ui-grid.aspx

Basically, you can add errors to the ModelState error collection on the server:

ModelState.AddModelError("SomsField", "Some error message.");

Then the Kendo ToDataSourceResult() function will put those ModelState errors into an errors collection in the JSON returned to the client.

On the client side, the DataSource's error function will be called when there are messages in the server response's error collection.

Then you can handle the errors in the DataSource error function.

您可以调用grid.cancelChanges()来防止数据源中发生任何未决的更改,如网址http://docs.kendoui.c​​om/api/web/grid#methods-cancelChanges中所述

Well, maybe you could go with the "edit" event of Kendo Grid. See docs here: http://docs.kendoui.com/api/web/grid#events-edit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM