We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. (Last updated on: June 24, 2019).
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

Modelstate errors

Thread ID:

Created:

Updated:

Platform:

Replies:

141722 Apr 12,2018 02:21 PM UTC Aug 24,2020 07:55 AM UTC ASP.NET Core - EJ 2 9
loading
Tags: DataGrid
ACM
Asked On April 12, 2018 02:21 PM UTC

Query: Is it possible to use the Modelstate.AddError() method to postback after CRUD operation fails???
               I have to catch specific errors on Database operations and want to return the fieldName and custom message  like for instance duplicate                    names i made the lines to handle this red

Like this:

@{Html.EJ().Grid<ModuleViewModel>("ModuleSetupGrid")
        .Datasource(src =>
        {
            src.URL("/ModuleSetup/Module_Read");
            src.InsertURL("/ModuleSetup/Module_Add");
            src.UpdateURL("/ModuleSetup/Module_Update");
            src.RemoveURL("/ModuleSetup/Module_Remove");
            src.Adaptor(AdaptorType.UrlAdaptor);
        })
        .Columns(col =>
        {
            col.Field("ModuleId").IsPrimaryKey(true).IsIdentity(true).Add();
            col.Field("ModuleName").Width(200).Add();
            col.Field("ModuleDescription").Width("80%").Add();
        })
        .AllowFiltering()
        .AllowPaging()
        .AllowSorting()
        .FilterSettings(filter => filter.FilterType(FilterType.Excel))
        .PageSettings(page => page.PageCount(3).PageSize(10))
        .EditSettings(edit =>
        {
            edit.AllowAdding()
                .AllowEditing()
                .AllowDeleting()
                .AllowAdding()
                .EditMode(EditMode.Dialog)
                .ShowDeleteConfirmDialog()
                .TitleColumn("ModuleName");
        })
        .ToolbarSettings(tb =>
        {
            tb.ShowToolbar().ToolbarItems(items =>
            {
                items.AddTool(ToolBarItems.Add);
                items.AddTool(ToolBarItems.Edit);
                items.AddTool(ToolBarItems.Delete);
            });
        }).ClientSideEvents(evt =>
      {
          evt.ActionFailure("afailure");
         
      }).Render();

//Grid events 
<script type="text/javascript">
     function afailure(e){
          alert(*/ here the modelstate.error should be shown /*);
     }
</script> 

#####
Controller for Insert opperation
#####

public IActionResult Module_Add([FromBody] CRUDModel<ModuleViewModel> model)
        {
           
                if (ModelState.IsValid && model != null)

                {
                    var result = new Module
                    {
                        ModuleId = model.Value.ModuleId,
                        ModuleName = model.Value.ModuleName,
                        ModuleDescription = model.Value.ModuleDescription
                    };
                    _repo.AddModule(result);
                    return Json(model.Value);
                }
                else
                {
                    ModelState.AddModelError("ModuleName", "This already exists");
                    return null; //how to return the error to grid???
                }
        }

thanks in advance.

Kuralarasan Muthusamy [Syncfusion]
Replied On April 13, 2018 01:32 PM UTC

Hi Alexander, 

Thanks for contacting Syncfusion support. 

We have analyzed the your given code and we found that you want to return the custom message from controller side to client side by using action-failure event of the Grid. We have achieved your requirement and we have prepared the sample with your requirement. 

Please refer the following code example: 

View Page: 
 
 
<ej-grid id="Grid" allow-paging="true" action-failure="failure"> 
 
              ... 
 
</ej-grid> 
 
<script type="text/javascript"> 
 
    function failure(args) { 
 
        alert(args.error.statusText); //get the exception message           
    }  
 
</script> 
 
 
 
Controller: 
 
namespace SyncfusionASPNETCoreApplication2.Controllers 
{ 
    public partial class GridController : Controller 
    { 
 
 
                      ..... 
 
        public ActionResult NormalInsert([FromBody]CRUDModel<Employees> value) 
        { 
            if (!ModelState.IsValid) //if validation got failed 
            { 
                var message = string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage)); 
                return new BadRequestObjectResult(HttpStatusCode.BadRequest);//message returns the exception content  
            } 
            emp.Insert(emp.Count, value.Value); 
            return Json(emp); 
        } 
         
                       ...... 
          
    } 
} 

 

In this code example we have used args.error.statusText in inside the action-failure event to get the controller side message to client side. 

We have already discussed about this issue in Syncfusion knowledge base document. Please refer the following link to kb: 


Please refer the following link to sample: 


Regards, 
Kuralarasan M. 


Chris
Replied On April 13, 2018 05:36 PM UTC

Hi ACM,

I've been following this thread because I want to do the same thing.  I got it working, but I'm pretty sure you want your error message to say something other then "Bad Request".  Here is how I did it:

I changed the controller code to this:

public ActionResult NormalInsert([FromBody]CRUDModel<Employees> value)
        {
            if (!ModelState.IsValid) //if validation failed
            {
                var message = string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage));
                BadRequestObjectResult badRequest = new BadRequestObjectResult(HttpStatusCode.BadRequest);
                badRequest.Value = message;
                return badRequest;
            }
            emp.Insert(emp.Count, value.Value);
            return Json(emp);
        }

I changed the javavascript failure method to this:

    function failure(args) {
 
        alert(args.error.responseText); //use responseText, not statusText          
    } 

If you want a nicer looking error message (not a javascript alert box), you could something like this:

In the controller:

public ActionResult NormalInsert([FromBody]CRUDModel<Employees> value)
        {
            if (!ModelState.IsValid) //if validation failed
            {
                var message = string.Join("<br>", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage));   // html break instead of " | "
                BadRequestObjectResult badRequest = new BadRequestObjectResult(HttpStatusCode.BadRequest);
                badRequest.Value = message;
                return badRequest;
            }
            emp.Insert(emp.Count, value.Value);
            return Json(emp);
        }

In your view add something like:

<ej-dialog id="CmtErrorList" title="Comment Error" show-on-init="false" close="onDialogClose"></ej-dialog>

I put it before the grid setup, I'm not sure if it matters where you put it.

Change the javascript failure function to:

        function failure(args) {
            var error = "<table><tr><td>" + args.error.responseText + "</td></tr></table>"
            $('#CmtErrorList').html("");
            $('#CmtErrorList').html(error)
            $('#CmtErrorList').ejDialog("open");

        }

Chris

ACM
Replied On April 16, 2018 11:33 AM UTC

tnx for the help got i working now. 

Using a custom dialog and posting my custom message to this.

@Chris if you want to show delete errors aswell u need to add this to you dialog script took me a wile to find this one:

if (e.error.responseText == null || e.error.responseText == undefined) {
            message = e.error.error.responseText;
        } 
        else {
            message = e.error.responseText;
        }
then post the message as you did the error.responseText


Kuralarasan Muthusamy [Syncfusion]
Replied On April 16, 2018 01:00 PM UTC

Hi Alexander, 

Please let us know if you need further assistance from Syncfusion support. 

Regards, 
Kuralarasan M. 


Chris
Replied On April 16, 2018 02:23 PM UTC

Thanks ACM!

Chris

Jason Gabel
Replied On December 27, 2018 08:20 PM UTC

I am using EJ2 Grid and I see that default operation still is not to add an overall validation feedback.
If you are going to have the URL adapter wouldn't it make sense to either:
  • Have it as default behavior on dialog or other edits
  • Have it extensible
The need to create a template every time seems odd (although may just add an extension myself), but typical razor form has something like:
@Html.ValidationSummary(true""new { @class = "text-danger" })

So you can do some server-side validation (which would be a legitimate reason for using the adapter) and utilize the ModelState.AddModelError the seems like a highly supportable feature.


Thavasianand Sankaranarayanan [Syncfusion]
Replied On January 2, 2019 10:59 AM UTC

Hi Jason, 

We have analyzed your requirement, the server side validation support is available in for EJ2 Grid from the 2018 Volume 4 release(16.4.42 ). You can use the server side validation feature from 16.4.42 like ejGrid. Please find the code example. 

Code example: 

View Page:  
  
  
<ejs-grid id="Grid" allowPaging="true" actionFailure="failure">  
  
              ...  
  
</ejs-grid>  
  
<script type="text/javascript">  
  
    function failure(args) {  
  
        alert(args.error.statusText); //get the exception message            
    }   
  
</script>  
  
  
  
Controller:  
  
namespace SyncfusionASPNETCoreApplication.Controllers  
{  
    public partial class GridController : Controller  
    {  
  
  
                      .....  
  
        public ActionResult NormalInsert([FromBody]CRUDModel<Employees> value)  
        {  
            if (!ModelState.IsValid//if validation got failed  
            {  
                var message = string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage));  
                return new BadRequestObjectResult(HttpStatusCode.BadRequest);//message returns the exception content   
            }  
        }  
     
                       ......  
           
    }  
}  



Note : Please update the EJ2 Grid to 16.4.42. 

Please let us know if you have any concerns. 

Regards, 
Thavasianand S. 


Cezar
Replied On August 21, 2020 07:28 PM UTC

Thavasianand Sankaranarayanan response and example is missing something to work!

  var message = string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage));  
  return new BadRequestObjectResult(HttpStatusCode.BadRequest);//message returns the exception content   

The message variable is not returned so it cannot be displayed.

Chris response did the trick!

  BadRequestObjectResult badRequest = new BadRequestObjectResult(HttpStatusCode.BadRequest);
  badRequest.Value = message;
  return badRequest;


Balaji Sekar [Syncfusion]
Replied On August 24, 2020 07:55 AM UTC

Hi Jason, 
 
We have validated your query with provided the information and we have achieved the Error handling in insert action. In the below code example, we have thrown the Exception in catch block while failed the insert action in server side then it will invoke the actionFailure in client side. Please refer the code example for more information. 
 
[Index.cshtml] 
ejs-grid id="Grid" allowPaging="true" actionFailure="actionFailure"  toolbar="@(new List<string>() {"Add", "Edit", "Update", "Delete" })"> 
    <e-data-manager url="/Home/UrlDataSource" adaptor="UrlAdaptor" insertUrl="/Home/Insert" updateUrl="/Home/Update" removeUrl="/Home/Remove"></e-data-manager> 
     
    .    .      .      . 
</ejs-grid> 
<script type="text/javascript">     
    function actionFailure(args) {     
        alert(args.error.statusText); //get the exception message 
    }   
</script>   
 
 
[HomeController.cs] 
 
  public IActionResult Insert([FromBody]CRUDModel<Orders> Value) 
        { 
            try 
            { 
                if (ModelState.IsValid) 
                { 
                    order.Insert(0, Value.Value); 
                } 
                return Json(Value.Value); 
                 
            } 
            catch (Exception e) { 
               
                throw new Exception(e.Message);//message returns the exception content    
            } 
        } 
 
Please get back to us , if you need further assistance. 
Regards, 
Balaji Sekar 


CONFIRMATION

This post will be permanently deleted. Are you sure you want to continue?

Sorry, An error occured while processing your request. Please try again later.

Please sign in to access our forum

This page will automatically be redirected to the sign-in page in 10 seconds.

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

Live Chat Icon For mobile
Live Chat Icon