如何从codebehind编辑Sitecore图像字段
本文关键字:Sitecore 图像 字段 编辑 codebehind | 更新日期: 2023-09-27 18:27:14
我有一个字段为"image
"的站点核心项"CurrentItem
"。我正在从代码后面编辑它,如下所示:
//Get the Image from /sitecore/media library/Images/Test
Item imageItem = Sitecore.Context.Database.GetItem("{AEBB3071-3462-405C-9CD3-A2B515B343D1}")
//Edit
CurrentItem.Editing.BeginEdit();
CurrentItem["image"] = imageItem.ToString();
CurrentItem.Editing.EndEdit();
PS:imageItem
是/sitecore/media library/Images/Test
下的图片
我也试过CurrentItem["image"] = imageItem.Paths.Path;
,但仍然没有成功。
您需要将字段设为ImageField
,并将MediaID属性设置为MediaItem:的ID
//Get the Image from /sitecore/media library/Images/Test
Sitecore.Data.Items.MediaItem imageItem = Sitecore.Context.Database.GetItem("{AEBB3071-3462-405C-9CD3-A2B515B343D1}")
//Edit
CurrentItem.Editing.BeginEdit();
var imageField = CurrentItem.Fields["image"] as ImageField;
imageField.MediaID = imageItem.ID;
imageField.MediaPath = imageItem.MediaPath;
CurrentItem.Editing.EndEdit();
你也可以看看这篇博客文章,了解更多关于6.X版本的解释。
您可以使用Sitecore.Data.Fields.ImageField类来更新图像字段。例如更新Master中/Sitecore/Content/Home项中名为ImageField的"图像"字段数据库到/Sitecore/Media Library/Images/Sample image:
Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
Sitecore.Data.Items.Item home = master.GetItem("/sitecore/content/home");
Sitecore.Data.Items.Item sampleItem =
master.GetItem("/sitecore/media library/images/sample");
Sitecore.Data.Items.MediaItem sampleMedia =
new Sitecore.Data.Items.MediaItem(sampleItem);
Sitecore.Data.Fields.ImageField imageField = home.Fields["imagefield"];
if (imageField.MediaID != sampleMedia.ID )
{
home.Editing.BeginEdit();
imageField.Clear();
imageField.Src = Sitecore.Resources.Media.MediaManager.GetMediaUrl(sampleMedia);
imageField.MediaID = sampleMedia.ID;
imageField.MediaPath = sampleMedia.MediaPath;
if (!String.IsNullOrEmpty(sampleMedia.Alt))
{
imageField.Alt = sampleMedia.Alt;
}
else
{
imageField.Alt = sampleMedia.DisplayName;
}
home.Editing.EndEdit();
}
请检查https://sdn.sitecore.net/upload/sitecore6/64/content_api_cookbook-usletter.pdf关于4.1.7如何访问图像字段