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. Image for the cookie policy date

Modelstate errors

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.

9 Replies

KM Kuralarasan Muthusamy Syncfusion Team April 13, 2018 09:32 AM

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. 



CH Chris April 13, 2018 01:36 PM

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


AC ACM April 16, 2018 07:33 AM

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



KM Kuralarasan Muthusamy Syncfusion Team April 16, 2018 09:00 AM

Hi Alexander, 

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

Regards, 
Kuralarasan M. 



CH Chris April 16, 2018 10:23 AM

Thanks ACM!

Chris


JG Jason Gabel December 27, 2018 03:20 PM

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.



TS Thavasianand Sankaranarayanan Syncfusion Team January 2, 2019 05:59 AM

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. 



CE Cezar August 21, 2020 03:28 PM

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;



BS Balaji Sekar Syncfusion Team August 24, 2020 03:55 AM

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 


Loader.
Live Chat Icon For mobile
Up arrow icon