Сетка Telerik, возможно ли добавить параметр Id в команды столбца?

C# asp.net 4.5, MS Visual Studio 2012, CMS nopcommerce и Telerik.

У меня есть следующие разделы кода:

Razor Просмотр..

<div>
        @(Html.Telerik().Grid<Hroc.Plugin.Misc.ImageGallery.Models.PictureModel.myPictureModel>()
                .Name("productpictures-grid")
                .DataKeys(x =>
                {
                    x.Add(y => y.Id).RouteKey("Id");
                })
                .Columns(columns =>
                {
                    columns.Bound(x => x.PictureUrl)
                        .ClientTemplate("<a href='<#= PictureUrl #>' target='_blank'><img alt='<#= PictureId #>' src='<#= PictureUrl #>' width='150' /><a/>")
                        .ReadOnly();
                    columns.Bound(x => x.DisplayOrder);
                    columns.Bound(x => x.Description);
                    columns.Command(commands =>
                    {
                        commands.Edit().Text(T("Admin.Common.Edit").Text); // can i pass the id here? as well as delete and update?
                        commands.Delete().Text(T("Admin.Common.Delete").Text);
                    });

                })
                .Editable(x =>
                {
                    x.Mode(GridEditMode.InLine);
                })
                .DataBinding(dataBinding =>
                {
                    dataBinding.Ajax().Select("PictureList", "ImageGallery")
                        .Update("GalleryPictureUpdate", "ImageGallery")
                        .Delete("GalleryPictureDelete", "ImageGallery");
                })
                .EnableCustomBinding(true))
</div>

Раздел controller для удаления обновления...

[GridAction(EnableCustomBinding = true)]
    public ActionResult GalleryPictureUpdate(PictureModel.myPictureModel model, GridCommand command)
    {
        var galleryPicture = _galleryItemService.GetGalleryPictureById(model.Id);//get selected id?
        if (galleryPicture == null)
            throw new ArgumentException("No product picture found with the specified id");

        galleryPicture.OrderNumber = model.DisplayOrder;
        _galleryItemService.UpdateGallerytPicture(galleryPicture);

        return PictureList(command);
    }

    [GridAction(EnableCustomBinding = true)]
    public ActionResult GalleryPictureDelete(PictureModel.myPictureModel model, GridCommand command)
    {
        var galleryPicture = _galleryItemService.GetGalleryPictureById(model.Id);
        if (galleryPicture == null)
            throw new ArgumentException("No product picture found with the specified id");

        var pictureId = galleryPicture.PictureID;

        _galleryItemService.DeleteProductPicture(galleryPicture);
        var picture = _pictureService.GetPictureById(pictureId);
        _pictureService.DeletePicture(picture);

        return PictureList(command);
    }

Мой раздел класса service...

 public virtual GalleryItem GetGalleryPictureById(int galleryPictureId)
    {
        if (galleryPictureId == 0)
            return null;

        return _ImageItemRepository.GetById(galleryPictureId);
    }

    public virtual void UpdateGallerytPicture(GalleryItem galleryPicture)
    {
        if (galleryPicture == null)
            throw new ArgumentNullException("galleryPicture");

        _ImageItemRepository.Update(galleryPicture);

        //event notification
        _eventPublisher.EntityUpdated(galleryPicture);
    }

    public virtual void DeleteProductPicture(GalleryItem galleryPicture)
    {
        if (galleryPicture == null)
            throw new ArgumentNullException("productPicture");

        _ImageItemRepository.Delete(galleryPicture);

        //event notification
        _eventPublisher.EntityDeleted(galleryPicture);
    }

Судя по предоставленному коду, все это находится в моем новом плагине (библиотеке классов) в nopcommerce.

По сути, когда вы настраиваете раздел плагина, отображаемый вид показывает список изображений, затем вы можете загрузить новое изображение в список, который затем отображается. Этот раздел работает нормально.

Команда «Редактировать» позволяет использовать параметры команды Telerik, поэтому вы можете изменить порядок отображения и описание. Однако, когда вы хотите обновить или удалить его, выдается исключение «не удается найти идентификатор».

Есть ли что-то, что мне здесь не хватает? Я считаю, что это потому, что я на самом деле не получаю конкретный идентификатор и не передаю его моему методу контроллера (где возникает ошибка).

любая помощь будет здорово!

ОБНОВЛЕНИЕ: 12.02.2013 по запросу вот код для получения списка изображений.

контроллер

[HttpPost, GridAction(EnableCustomBinding = true)]
    public ActionResult PictureList(GridCommand command)
    {
        if (!_permissionService.Authorize(StandardPermissionProvider.ManagePlugins))
            return Content("Access denied");

        var nop_Image = _galleryItemService.Fetch(); //my image

        var Nop_ImagesModel = nop_Image
            .Select(x =>
            {
                var nop_gModel = new PictureModel.myPictureModel()
                {
                    PictureId = x.Id,
                    PictureUrl = _pictureService.GetPictureUrl(x.PictureID),
                    DisplayOrder = x.OrderNumber,
                    Description = x.Description
                };

                return nop_gModel;
            })
            .ToList();

        var model = new GridModel<PictureModel.myPictureModel>
        {
            Data = Nop_ImagesModel, 
        };

        return new JsonResult
        {
            Data = model
        };
    }

Обновление: 12.02.2013 по запросу

[GridAction(EnableCustomBinding = true)]
    public ActionResult GalleryPictureDelete(PictureModel.myPictureModel model, GridCommand command)
    {
        var galleryPicture = _galleryItemService.GetGalleryPictureById(model.PictureId);
        if (galleryPicture == null)
            throw new ArgumentException("No product picture found with the specified id");

        var pictureId = galleryPicture.PictureID;

        _galleryItemService.DeleteProductPicture(galleryPicture);
        var picture = _pictureService.GetPictureById(pictureId);
        _pictureService.DeletePicture(picture);

        return PictureList(command);
    }

вид

<div>
             @(Html.Telerik().Grid<@Hroc.Plugin.Misc.ImageGallery.Models.PictureModel.myPictureModel>()
                .Name("productpictures-grid")
                .DataKeys(x =>
                {
                    x.Add(y => y.Id).RouteKey("Id");
                })
                .Columns(columns =>
                {
                    columns.Bound(x => x.PictureId).Hidden(true); 
                    columns.Bound(x => x.PictureUrl)
                        .ClientTemplate("<a href='<#= PictureUrl #>' target='_blank'>    <img alt='<#= PictureId #>' src='<#= PictureUrl #>' width='150' /><a/>")
                        .ReadOnly();
                    columns.Bound(x => x.DisplayOrder);
                    columns.Bound(x => x.Description);
                    columns.Command(commands =>
                    {
                        commands.Edit().Text(T("Admin.Common.Edit").Text); 
                        commands.Delete().Text(T("Admin.Common.Delete").Text);
                    });
                })

                .Editable(x =>
                {
                    x.Mode(GridEditMode.InLine);
                })
                .DataBinding(dataBinding =>
                {
                    dataBinding.Ajax().Select("PictureList", "ImageGallery")
                        .Update("GalleryPictureUpdate", "ImageGallery")
                        .Delete("GalleryPictureDelete", "ImageGallery");
                })
                .EnableCustomBinding(true))
</div>

person lemunk    schedule 29.11.2013    source источник
comment
пожалуйста, отправьте код для получения списка изображений   -  person Nitin Varpe    schedule 30.11.2013


Ответы (1)


Единственное, что вам нужно сделать, это назначить идентификатор, а не pictureId, и сохранить свой первый код как есть.

.DataKeys(x =>
                {
                    x.Add(y => y.Id).RouteKey("Id");
                })



 var nop_gModel = new PictureModel.myPictureModel()
                {
                    Id = x.Id,//Changed as you are getting picture by Id
                    PictureUrl = _pictureService.GetPictureUrl(x.PictureID),
                    DisplayOrder = x.OrderNumber,
                    Description = x.Description
                };



var galleryPicture = _galleryItemService.GetGalleryPictureById(model.Id);
person Nitin Varpe    schedule 02.12.2013
comment
извините, это не имело значения - person lemunk; 02.12.2013
comment
где именно выдает ошибку, во время обновления записи? он попадает в точку останова. какие ошибки есть в ModelState? Проверить обновление - person Nitin Varpe; 02.12.2013
comment
это помогло, обновление теперь работает, однако то же самое не сказано о действии удаления. возвращает 0 для идентификатора - person lemunk; 02.12.2013
comment
Вы сделали то же самое для удаления, а не для идентификатора PictureId в вашем случае - person Nitin Varpe; 02.12.2013
comment
да, идентификатор возвращается 0, я полагаю, это связано с тем, что идентификатор не возвращается в список - person lemunk; 02.12.2013
comment
я переключился на id и проверил, поэтому я поместил его в список, он возвращается с правильным идентификатором (не pictureid), но мой getmethod пытается найти идентификатор изображения в этом случае. Так должен ли я по-прежнему использовать pictureid? если да, то в чем проблема, ИЛИ, я должен использовать идентификатор и создать новый метод получения в моей службе - person lemunk; 02.12.2013
comment
И да, вам нужно передать Id, а не PictureId, поскольку вы используете GetById - person Nitin Varpe; 02.12.2013
comment
пока работает! плохо сделать некоторые тесты, но я думаю, что все отсортировано! - person lemunk; 02.12.2013
comment
после тестирования я присуждаю вам награду (присуждение занимает 24 часа) - person lemunk; 02.12.2013
comment
Нет проблем, с удовольствием - person Nitin Varpe; 02.12.2013