首页 > 解决方案 > Syncfusion Asp.Net Datagrid:如何从 CRUD 类返回错误

问题描述

我有一个 Syncfusion Asp.net 网格执行 CRUD 操作。

public ActionResult Insert(CRUDModel<Source> newItem)
{
    using (var context = new ImageStormEntities())
    {
        context.Sources.Add(newItem.Value);
        context.SaveChanges();
    }

    return Json(newItem.Value);
}

cshtml:

@Html.EJS().Grid("DataGrid").DataSource(ds => ds.Json(ViewBag.datasource).UpdateUrl("/Management/Update").InsertUrl("/Management/Insert").RemoveUrl("/Management/Remove").Adaptor("RemoteSaveAdaptor")).Columns(col =>
{

    col.Field("id").IsPrimaryKey(true).Visible(false).Add();
    col.Field("ResourceGroup").HeaderText("Source VM Resource Group").Add();
    col.Field("VMName").HeaderText("Source VM Name").Add();
    col.Field("imageVersion").HeaderText("Image Version").Add();

}).ActionFailure("OnActionFailure").AllowTextWrap(true).TextWrapSettings(text => { text.WrapMode(Syncfusion.EJ2.Grids.WrapMode.Header); }).AllowPaging().FilterSettings(filter => { filter.Type(Syncfusion.EJ2.Grids.FilterType.Menu); }).EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).ShowDeleteConfirmDialog(true).Mode(Syncfusion.EJ2.Grids.EditMode.Dialog); }).Toolbar(new List<string>
    () { "Add", "Edit", "Delete", "Update", "Cancel" }).Render()

在页面上,我有:

<script>
    function OnActionFailure(args) {
        alert(args.error.status + " : " + args.error.statusText);
    }
</script>

当值打破 db 约束但值为空时,它会返回一条简单的 toast 消息。我想向用户发送有用的信息。

我可以捕捉到错误,我应该返回什么来完成这项工作。另外,我宁愿使用 Messagebox 来释放而不是敬酒。

标签: asp.net-mvcsyncfusion

解决方案


更改了您的控制器代码,这将解决您的问题

public ActionResult Insert(CRUDModel<Source> newItem)
{
  using (var context = new ImageStormEntities())
    {
     if(newItem.Value! = null)
     {
        context.Sources.Add(newItem.Value);
        context.SaveChanges();
     }
     else
     {
        throw new Exception("Empty values cannot be inserted");//Add custom 
        exception message 
     } 
    }

 return Json(newItem.Value);
}

并在你的 js 中添加石灰这个

<script> 
   function OnActionFailure(args) { 
     var errorMessage = args[0].error.responseText.split("Exception:")[1].split('<br>')[0];  //extract the message from args 
    alert(errorMessage); 
    //you will get exact error that you have returned from serverside in errorMessage
 } 
</script> 

推荐阅读