虚拟 属性 只读 - 无法更改其值

Virtual property readonly - unable to change its value

我正在尝试将数据库中的值动态分配给继承自 EpiServer PageData class 的 属性。这就是我的意思:

namespace Episerver9.Models.Pages
{
    [ContentType]
    public class StartPage : PageData
    {
        public virtual string Username { get; set; }
        public virtual string Password { get; set; }
        public virtual string FirstName { get; set; }
        public virtual string LastName { get; set; }

        [ReadOnly(false)]
        [Editable(true)]
        public virtual string testfield { get; set; }


    }
}

在控制器中我正在尝试以下操作:

namespace Episerver9.Controllers
{
    public class StartPageController : PageController<StartPage>
    {
        // GET: StartPage

        public ActionResult Index(StartPage currentPage)
        {
            currentPage.testfield = "test";
            return View(currentPage);
        }
    }
}

这就是我要在视图中显示的内容:

@Html.PropertyFor(x=>x.testfield)
// Trying to dynamically populate the data from code, later on from DB

我得到的错误是:

Additional information: The property testfield is read-only

即使我为 属性 明确指定它不是只读的,也会发生这种情况...有人知道为什么吗?

这是因为 ContentData 对象出于性能目的始终是只读的。要更改任何属性,您必须创建一个 可写克隆 ,例如:

currentPage.CreateWritableClone()

这将为您提供一个您可以更改的页面实例,例如使用 IContentRepository 实例保存更改。

但是请注意,这些实例是只读的是有原因的。 :) 您最好创建一个传递给视图的单独视图模型。