To make a property readonly in Episerver, you can use the ReadOnly
attribute in your model class. This attribute can be applied to both properties and fields and prevents them from being modified by editors in the Episerver CMS.
Here's an example of how to use the ReadOnly
attribute:
csharpusing EPiServer.Core;
using EPiServer.DataAnnotations;
public class MyPageType : PageData
{
[Display(
Name = "My Read-Only Property",
Description = "This property is read-only.",
Order = 1
)]
[ReadOnly(true)]
public string MyReadOnlyProperty { get; private set; }
}
In this example, the MyReadOnlyProperty
is marked as readonly by applying the ReadOnly
attribute with a value of true
. The property also has a private setter, which ensures that the value can only be set within the class itself.
When an editor tries to modify the value of this property in the Episerver CMS, the UI will prevent them from doing so and show a message indicating that the property is read-only.
Note that the ReadOnly
attribute only affects the Episerver CMS UI and does not prevent the property from being modified programmatically. If you need to prevent modifications to the property within your code, you'll need to add additional checks or use a different approach, such as making the property private and providing a read-only getter method.
Comments
Post a Comment