asp.net-mvc - 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 来释放而不是敬酒。
解决方案
更改了您的控制器代码,这将解决您的问题
至
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>
推荐阅读
- c# - 使用 X509 证书通过 Azure AD 对应用程序进行身份验证
- mongodb - 升级后,Mongodb Atlas 开始出现 IOPS 和页面错误,并且查询速度非常慢
- c# - 列表
在 foreach 循环中复制列表项中的相同数据 - aws-amplify - Docusaurus 与现有的 AWS 放大
- flutter - 在 Flutter 中过滤掉电影
- .htaccess - 主要和次要 .htaccess 中的“嵌套”RewriteRule
- javascript - 返回函数数组的计算属性在这些函数中失去了 this 的范围
- firebase - Browsers block CORS cookie
- mapstruct - Mapstruct 将枚举名称映射到代码,反之亦然
- python - 打印列表元素时如何删除逗号(,)?