1

我正在编写一段代码以防止 Telerik Grid 联系服务器以保存重复的数据。这是我到目前为止所拥有的。

看法

@(Html.Telerik().Grid<CategoryModel.CategoryUnitsModel>()
                    .Name("categoryunits-grid")
                    .DataKeys(keys =>
                    {
                        keys.Add(x => x.Id);
                        keys.Add(x => x.CategoryId);
                        keys.Add(x => x.UnitId);
                    })
                    .DataBinding(dataBinding =>
                    {
                        dataBinding.Ajax()
                            .Select("CategoryUnitsList", "Category", new { categoryId = Model.Id })
                            .Insert("CategoryUnitsInsert", "Category", new { categoryId = Model.Id })
                            .Update("CategoryUnitsInsert", "Category", new { categoryId = Model.Id })
                            .Delete("CategoryUnitsDelete", "Category", new { categoryId = Model.Id });
                    })
                    .Columns(columns =>
                    {
                        columns.Bound(x => x.UnitId)
                            .Visible(false);
                        columns.Bound(x => x.UnitText);
                        columns.Command(commands =>
                        {
                            commands.Edit();
                            commands.Delete();
                        })
                       .Width(100);
                    })
                    .ToolBar(commands => commands.Insert())
                    .Pageable(settings => settings.PageSize(gridPageSize).Position(GridPagerPosition.Both))
                    .ClientEvents(events => events.OnRowDataBound("onRowDataBound"))
                    .ClientEvents(events => events.OnSave("onSave"))
                    .EnableCustomBinding(true))

<script type="text/javascript">
                    function onRowDataBound(e) {
                        $(e.row).find('a.t-grid-edit').remove(); //remove Delete button
                    }

                    function onSave(e) {
                        $.getJSON('@Url.Action("CheckForCategoryUnit", "Category")', { categoryId: $("#Id").val(), unitId: $("#UnitText").val() }, function (data) {
                            if (data) {
                                alert("Units may not be added twice for a category");
                                e.preventDefault();
                            }
                            else {

                            }
                        });
                    }
                </script>

控制器

[HttpPost, GridAction(EnableCustomBinding = true)]
    public ActionResult CategoryUnitsList(GridCommand command, int categoryId)
    {
        if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
            return AccessDeniedView();

        var categoryUnits = _categoryService.GetCategoryUnits(categoryId, command.Page - 1 , command.PageSize);
        var categoryUnitsModel = PrepareCategoryUnitsModel(categoryUnits);

        var model = new GridModel<CategoryModel.CategoryUnitsModel>
        {
            Data = categoryUnitsModel,
            Total = categoryUnitsModel.Count
        };

        return new JsonResult
        {
            Data = model
        };
    }

    public ActionResult CheckForCategoryUnit(int categoryId, int unitId)
    {
        var categoryUnit = _categoryService.GetCategoryUnitByCategoryIdAndUnitId(categoryId, unitId);
        return Json(categoryUnit != null, JsonRequestBehavior.AllowGet);
    }

    [GridAction(EnableCustomBinding = true)]
    public ActionResult CategoryUnitsInsert(GridCommand command, CategoryModel.CategoryUnitsModel model)
    {
        if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
            return AccessDeniedView();

        var categoryUnit = new CategoryUnits
        {
            UnitId = Int32.Parse(model.UnitText),
            CategoryId = model.CategoryId
        };

        _categoryService.InsertCategoryUnit(categoryUnit);

        return CategoryUnitsList(command, model.CategoryId);
    }

此时,我收到一条警报,提示我在我的 ajax 中点击。但是, e.preventDefault() 并没有阻止服务器继续前进并保存我的数据。关于这个问题,我尝试了几种不同的方法,包括:

返回 false,e.stop(),e.returnValue = false,e.stopPropagation()。

到目前为止还没有工作。如果有人有任何想法,我愿意接受。我拥有的操作系​​统和浏览器的组合是 Windows XP 和 IE8。只是添加以防万一。谢谢。

最诚挚的问候,查德·约翰逊

4

4 回答 4

1

感谢您到目前为止的回复。我也尝试过 e.returnValue ,但不幸的是,它像其他人一样失败了,Nathalie。

我实际上想出了一个类似于 IronMan84 的解决方案。

我没有使用 OnSave,而是等到在控制器上插入期间检查重复数据。这是我想出的:

控制器:

[GridAction(EnableCustomBinding = true)]
    public ActionResult CategoryUnitsInsert(GridCommand command, CategoryModel.CategoryUnitsModel model)
    {
        if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
            return AccessDeniedView();

        var searchForEntry = _categoryService.GetCategoryUnitByCategoryIdAndUnitId(model.CategoryId, Int32.Parse(model.UnitText));
        if (searchForEntry != null)
        {
            var scriptText = "alert('Units may not be added twice for a category');";
            return JavaScript(scriptText);
        }

        var categoryUnit = new CategoryUnits
        {
            UnitId = Int32.Parse(model.UnitText),
            CategoryId = model.CategoryId
        };

        _categoryService.InsertCategoryUnit(categoryUnit);

        return CategoryUnitsList(command, model.CategoryId);
    }

我只是在重复数据的情况下返回了一个 JavaScript 操作。谢谢大家的帮助。

于 2012-10-23T17:48:30.973 回答
0

我也在我的应用程序中进行了类似的检查,但我以不同的方式处理它。我没有尝试在 AJAX 中保存时发出警告,而是在我的控制器中进行了操作。如果它发现任何重复项,它将在 ViewData 字典中设置一个值。然后,在我的主页上,我有一个警告框,将显示该值。

if(ViewData.ContainsKey("PopupMessage"))
    {
        var message = ViewData["PopupMessage"].ToString();
        <script type="text/javascript">
            window.alert('@message');
        </script>
    }
于 2012-10-23T15:21:47.883 回答
0

IE 中的事件没有 preventDefault。

看看这个线程:preventdefault Alternative for ie8

对于 IE,您必须使用:e.returnValue

(e.preventDefault) ? e.preventDefault() : e.returnValue = false; 
于 2012-10-23T15:22:07.810 回答
0

好吧,伙计们,我想出了一个完全不同的解决方案。但是,我确实还有另一个问题想问。

首先,这就是我所做的。我没有捕捉到何时重复数据,而是从下拉列表中删除了该数据,这样该选项就不会发生。除此之外,我现在动态加载下拉列表,从而保持数据新鲜并避免重复。

看法

var gridPageSize = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().GridPageSize;
    <table class="adminContent">
        <tr>
            <td>
                @(Html.Telerik().Grid<CategoryModel.CategoryUnitsModel>()
                    .Name("categoryunits-grid")
                    .DataKeys(keys =>
                    {
                        keys.Add(x => x.Id);
                        keys.Add(x => x.CategoryId);
                        keys.Add(x => x.UnitId);
                    })
                    .DataBinding(dataBinding =>
                    {
                        dataBinding.Ajax()
                            .Select("CategoryUnitsList", "Category", new { categoryId = Model.Id })
                            .Insert("CategoryUnitsInsert", "Category", new { categoryId = Model.Id })
                            .Update("CategoryUnitsInsert", "Category", new { categoryId = Model.Id })
                            .Delete("CategoryUnitsDelete", "Category", new { categoryId = Model.Id });
                    })
                    .Columns(columns =>
                    {
                        columns.Bound(x => x.UnitId)
                            .Visible(false);
                        columns.Bound(x => x.UnitText);
                        columns.Command(commands =>
                        {
                            commands.Edit();
                            commands.Delete();
                        })
                        .Width(100);
                    })
                    .ToolBar(commands => commands.Insert())
                    .Pageable(settings => settings.PageSize(gridPageSize).Position(GridPagerPosition.Both))
                    .ClientEvents(events => events.OnRowDataBound("onRowDataBound"))
                    .ClientEvents(events => events.OnEdit("onEdit"))
                    .EnableCustomBinding(true))

                <script type="text/javascript">
                    function onRowDataBound(e) {
                        $(e.row).find('a.t-grid-edit').remove(); //remove Delete button
                    }

                    function onEdit(e) {
                        $.getJSON('@Url.Action("LoadAvailableUnits", "Category")', { categoryId: $("#Id").val() }, function (data) {
                            var ddl = $("#UnitText").data("tDropDownList");
                            if (data.length > 0) {
                                ddl.dataBind(data);
                                ddl.reload();
                            }
                            else {
                                $('a[class="t-button t-grid-cancel"]').click();
                                alert("There are no Units left to select from");
                            }
                        });
                    }
                </script>

EditorTemplates/CategoryUnit.cshtml

@using Telerik.Web.Mvc.UI;
@Html.Telerik().DropDownList().Name("UnitText")

我的模型是一样的。

控制器

[HttpPost, GridAction(EnableCustomBinding = true)]
    public ActionResult CategoryUnitsList(GridCommand command, int categoryId)
    {
        if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
            return AccessDeniedView();

        var categoryUnits = _unitsService.GetCategoryUnits(categoryId, command.Page - 1, command.PageSize);
        var categoryUnitsModel = PrepareCategoryUnitsModel(categoryUnits);

        var model = new GridModel<CategoryModel.CategoryUnitsModel>
        {
            Data = categoryUnitsModel,
            Total = categoryUnitsModel.Count
        };

        return new JsonResult
        {
            Data = model
        };
    }

    public JsonResult LoadAvailableUnits(int categoryId)
    {
        var categoryUnits = _unitsService.GetAvailableUnits(categoryId);
        var categoryUnitsModel = PrepareAvailableUnitsInModel(categoryUnits);
        var returnData = new SelectList(categoryUnitsModel, "UnitId", "UnitText");
        return Json(returnData, JsonRequestBehavior.AllowGet);
    }

    [GridAction(EnableCustomBinding = true)]
    public ActionResult CategoryUnitsInsert(GridCommand command, CategoryModel.CategoryUnitsModel model)
    {
        if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
            return AccessDeniedView();

        var searchForEntry = _unitsService.GetCategoryUnitByCategoryIdAndUnitId(model.CategoryId, Int32.Parse(model.UnitText));
        if (searchForEntry != null)
        {
            return CategoryUnitsList(command, model.CategoryId);
        }

        var categoryUnit = new CategoryUnits
        {
            UnitId = Int32.Parse(model.UnitText),
            CategoryId = model.CategoryId
        };

        _unitsService.InsertCategoryUnit(categoryUnit);

        return CategoryUnitsList(command, model.CategoryId);
    }

    [GridAction(EnableCustomBinding = true)]
    public ActionResult CategoryUnitsDelete(GridCommand command, CategoryModel.CategoryUnitsModel model, int id)
    {
        if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
            return AccessDeniedView();

        var categoryId = model.CategoryId;
        _unitsService.DeleteCategoryUnit(model.CategoryId, id);

        return CategoryUnitsList(command, categoryId);
    }

我的新问题是分页不起作用。我不确定为什么它没有,因为我并没有真正搞砸它。我怀疑这与我加载网格的方式有关。任何帮助,将不胜感激。

于 2012-10-24T19:49:55.553 回答