For this example, the default grid configuration has been used.
Grid configuration
Set value
See the example below to see how a value can be added or changed programmatically. To update a value of a property editor you need the Content Service.
@using Newtonsoft.Json@using Umbraco.Cms.Core.Services;@using Umbraco.Cms.Core.Models;@inject IContentService Services;@{ // Get access to ContentServicevar contentService = Services; // Create a variable for the GUID of the page you want to updatevar guid =Guid.Parse("32e60db4-1283-4caa-9645-f2153f9888ef"); // Get the page using the GUID you've definedvar content =contentService.GetById(guid); // ID of your page // Create a variable for the grid value with the 1 one column layout and add a headlinevar gridValue =newGridValue { Name ="1 column layout", Sections =newList<GridValue.GridSection> {newGridValue.GridSection { Rows =newList<GridValue.GridRow> {newGridValue.GridRow { Name ="Headline", Id =newGuid(), Areas =newList<GridValue.GridArea> {newGridValue.GridArea { Controls =newList<GridValue.GridControl> {newGridValue.GridControl { Editor =newGridValue.GridEditor { Alias ="headline" }, Value ="Our Umbraco" } } } } } } } } }; // Serialize the grid valuevar serializedGridValue =JsonConvert.SerializeObject(gridValue); // Set the value of the property with alias 'body'content.SetValue("body", serializedGridValue); // Save the changecontentService.Save(content);}
Although the use of a GUID is preferable, you can also use the numeric ID to get the page:
@{ // Get the page using it's idvar content =contentService.GetById(1234); }
If Modelsbuilder is enabled you can get the alias of the desired property without using a magic string:
@using Umbraco.Cms.Core.PublishedCache;@inject IPublishedSnapshotAccessor _publishedSnapshotAccessor;@{ // Set the value of the property with alias 'body'content.SetValue(Home.GetModelPropertyType(_publishedSnapshotAccessor, x =>x.Body).Alias, serializedGridValue);}