我正在编写一段代码以防止 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。只是添加以防万一。谢谢。
最诚挚的问候,查德·约翰逊