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

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

问题描述

我有一个实体位置和我使用的UI Kendu电网与联编辑模式。
该实体拥有属性的显示名称的,这是需要和必须不存在两次在数据库中。

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.

目前,它的工作原理来显示必需的验证消息:

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

和它也可以建立一个方法 CustomValidateModel 称为在 LocationController 阿贾克斯内联创建方法,以及检查该名称是否已经在数据库中存在的增加则一个 ModelError 。我抓住这个错误,那么在 .Events(事件=> events.Error(onError的))通过JavaScript,然后显示通过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弹出后。
但是对于实用性,我想,新的线路和输入仍然存在。用户应该能够编辑给定的名字,他想拯救。而不应再次输入完整产品线。只有验证消息名称已经存在。应及时了解相关信息。

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.

code:

地点实体:

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

LocationController操作方法:

[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:\n";
        $.each(e.errors, function (key, value) {
            if (value.errors) {
                message += value.errors.join("\n");
            }
        });
        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电网剃刀:

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:\n";

        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>

LocationController.cs

LocationController.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.");
        }
    }

结果:

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

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