简体   繁体   English

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

[英]Virtual property readonly - unable to change its value

I'm trying to dynamically assign a value from DB to a property which inherits from EpiServer PageData class. 我正在尝试动态地将DB中的值分配给继承自EpiServer PageData类的属性。 Here is what I mean: 这是我的意思:

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; }


    }
}

And in controller I'm trying the following: 在控制器中,我正在尝试以下操作:

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

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

And this is what I'm trying to display in the view: 这就是我要在视图中显示的内容:

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

The error that I'm getting is: 我得到的错误是:

Additional information: The property testfield is read-only

This happens even tho I clearly specified for the property that IT IS NOT read only... Does anyone knows why? 甚至在我明确指定其属性不是只读的情况下,也会发生这种情况。有人知道为什么吗?

This is because ContentData objects are always read-only for performance purposes. 这是因为出于性能目的, ContentData对象始终是只读的。 To change any properties, you have to create a writable clone like: 要更改任何属性,您必须创建一个可写克隆,例如:

currentPage.CreateWritableClone()

That will give you an instance of your page that you can change, for example to save changes using an IContentRepository instance. 这将为您提供您可以更改的页面实例,例如,使用IContentRepository实例保存更改。

However, note that these instances are read-only for a reason. 但是,请注意,由于某些原因,这些实例是只读的。 :) You're better off creating a separate view model that you pass to your view. :)最好创建一个传递给视图的单独的视图模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM