Kendo Grid 编辑内联自定义验证消息,例如对于重复名称等 [英] Kendo Grid Edit InLine Custom Validation message e.g. for duplicate Names etc

查看:13
本文介绍了Kendo Grid 编辑内联自定义验证消息,例如对于重复名称等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体 Location 并且我正在使用具有内联编辑模式的 Kendu UI 网格.该实体拥有一个属性 DisplayName,该属性是必需的,并且不得在数据库中出现两次.

I have an entity Location and I am using the Kendu UI Grid with InLine edit mode. The entity owns a property DisplayName, which is required and must not exist twice in the database.

目前,它可以显示 Required 验证消息:

At the moment, it works to display the Required Validation message:

它还可以构建一个在 LocationController Ajax InLine Create 方法中调用的方法 CustomValidateModel,该方法检查 Name 是否已经存在于数据库中,然后添加模型错误.然后我通过 javascript 在 .Events(events => events.Error("onError")) 中捕捉到这个错误,然后通过 javascript 弹出窗口显示消息.

And it also works to build up a method CustomValidateModel called in the LocationController Ajax InLine Create method, that checks if the Name is already existing in the database and adds then a ModelError. I catch this error then in the .Events(events => events.Error("onError")) via javascript and show then the message via javascript popup.

ModelState.AddModelError("DisplayName", "Name already exists.");

这就是问题的症结所在:我不想看到这个 javascript 弹出消息.我还想在字段下方显示此信息,例如需要字段!"信息.我已经搜索了很多时间,但大多数人只建议通过 javascript 进行验证和输出,因为它目前有效.

And this is the crux of the matter: I don't want to have this javascript popup message. I want to have also this information below the field, like this "Field required!" message. I have searched plenty of time, but the most people suggest only this Validation and output via javascript as it works in the moment.

此外,除了弹出窗口之外的实际问题是,用户想要在网格中创建的记录在确认 javascript 弹出窗口后消失.但是为了可用性,我希望新行和输入保持不变.用户应该能够编辑给定的名称,他想保存.并且 NOT 应该再次输入完整的行.只有验证消息名称已存在".应该提示输入信息.

Additionally, the actual problem besides the popup, is, that the record, which the user wants to create in the Grid, is then disappearing after confirming the javascript popup. But for usability, I want that the new line and the input persists. The users should be able to edit the given Name, he wanted to save. And NOT should enter the complete line again. Only the Validation message "Name already existing." should prompt for information.

代码:

位置实体:

public class LocationDto
{
    public Guid? ID { get; set; }
    [Required(AllowEmptyStrings = false, ErrorMessage = "Field required!")]
    public string DisplayName { get; set; }
    // other properties
}

LocationController Action 方法:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CreateInline([DataSourceRequest] DataSourceRequest request, LocationDto model)
{
    CustomValidateModel(model); // checks if the DisplayName is already existing in the DB
    if (model != null && ModelState.IsValid)
    {
        // Create and Save the Model into database
    }
    return Json(ModelState.ToDataSourceResult());
}

javascript 函数:

function onError(e, status) {
    if (e.errors) {
        var message = "Error:
";
        $.each(e.errors, function (key, value) {
            if (value.errors) {
                message += value.errors.join("
");
            }
        });
        this.cancelChanges();
        alert(message);
    }
}

我希望有可能以同样的方式使其工作.根据一致的可视化和可用性的增强就可以了.

I hope there is a possibility to get this working in the same way. It would be fine according congruent visualization and an enhancement of usability.

推荐答案

通过修改另一个答案并尝试,我构建了一个可行的解决方案:

With modifying of another answer and trying around, I constructed a working solution:

位置 Edit.cshtml Grid Razor:

Location Edit.cshtml Grid Razor:

.DataSource(ds => ds
    .Ajax()
    .Events(e => e.Error("onError"))
    .Model(m =>
        {
            m.Id(e => e.ID);
            ...
        })
    .Create(create => create.Action("CreateInLine", "Location"))
    .Read(...)
    .Update(update => update.Action("UpdateInLine", "Location"))
    .Destroy(...)
)

位置 Edit.cshtml js:

Location Edit.cshtml js:

<script type="text/javascript">
function onError(e, status) {
    if (e.errors) {
        var message = "Error:
";

        var grid = $('#locationGrid').data('kendoGrid');
        var gridElement = grid.editable.element;

        var validationMessageTemplate = kendo.template(
            "<div id='#=field#_validationMessage' " +
                "class='k-widget k-tooltip k-tooltip-validation " +
                    "k-invalid-msg field-validation-error' " +
                "style='margin: 0.5em;' data-for='#=field#' " +
                "data-val-msg-for='#=field#' role='alert'>" +
                "<span class='k-icon k-warning'></span>" +
                "#=message#" +
                "<div class='k-callout k-callout-n'></div>" +
            "</div>");

        $.each(e.errors, function (key, value) {
            if (value.errors) {
                gridElement.find("[data-valmsg-for=" + key + "],[data-val-msg-for=" + key + "]")
                    .replaceWith(validationMessageTemplate({ field: key, message: value.errors[0] }));
                gridElement.find("input[name=" + key + "]").focus();
            }
        });
        grid.one("dataBinding", function (e) {
            e.preventDefault();   // cancel grid rebind
        });
    }
}
</script>

位置控制器.cs

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult CreateInLine([DataSourceRequest] DataSourceRequest request, LocationViewModel model)
    {
        CustomValidateModel(model);
        if (model != null && ModelState.IsValid)
        {
            var location = _repository.CreateNewInstance<Location>();
            location.ID = Guid.NewGuid();
            location.DisplayName = model.DisplayName;
            ...
            _repository.SaveChanges();
            model = MapToViewModel(location);
        }
        return Json(new[] { model }.ToDataSourceResult(request, ModelState));
    }

    private void CustomValidateModel(LocationViewModel model)
    {
        var existingEntity = _repository.GetAll<Location>()
                                            .Where(o => o.ID != model.ID)
                                            .Where(o => o.DisplayName.Equals(model.DisplayName))
                                            .FirstOrDefault();

        if (existingEntity != null)
        {
            if (existingEntity.Deleted == false)
                ModelState.AddModelError("DisplayName", "Name already exists.");
            else
                ModelState.AddModelError("DisplayName", "Name '" + existingEntity.DisplayName + "' already exists in DB, but deleted.");
        }
    }

结果:

这篇关于Kendo Grid 编辑内联自定义验证消息,例如对于重复名称等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆