nv.snow
nv.snow

Reputation: 934

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?

Upvotes: 1

Views: 5354

Answers (3)

CodingWithSpike
CodingWithSpike

Reputation: 43698

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.

Upvotes: 3

Ken W
Ken W

Reputation: 999

You can call the grid.cancelChanges() to prevent any pending changes in the dataSource as stated in the url http://docs.kendoui.com/api/web/grid#methods-cancelChanges

Upvotes: 1

Stargazer
Stargazer

Reputation: 472

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

Upvotes: 0

Related Questions