【问题标题】:Mark a field "Read Only" with Data Annotations使用数据注释将字段标记为“只读”
【发布时间】:2013-05-03 12:44:31
【问题描述】:

我正在尝试将ID 字段设为只读。它是数据库中的一个身份字段,因此用户不会设置它。然而,他们希望看到它。我在下面缺少什么,当分配给 DataForm 时仍然允许编辑该值。

public class StatusChoice : BindableBase
{
    private int id;

    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Editable(false,AllowInitialValue = false)]
    public int ID
    {
        get { return id; }
        set
        {
            id = value;
            OnPropertyChanged();
        }
    }
}

【问题讨论】:

    标签: c# .net telerik data-annotations


    【解决方案1】:

    使用 ReadOnly 属性标记属性。

    [ReadOnly(true)]
    public decimal BodyMassIndex { get; private set; }
    

    点击以下链接了解更多 Has the behavior for DataAnnotations in asp.net mvc 3 changed?

    【讨论】:

      【解决方案2】:

      根据情况,您通常有两种选择。

      [Editable(false)] or [ReadOnly(true)]

      以下是来自 MSDN 的描述

      System.ComponentModel.ReadOnlyAttribute
      

      https://msdn.microsoft.com/en-us/library/system.componentmodel.readonlyattribute%28v=vs.110%29.aspx

      指定此属性绑定到的属性是只读的还是读/写的。 标记为 ReadOnlyAttribute 设置为 true 或没有 Set 方法的成员不能更改。没有此属性或标记为 ReadOnlyAttribute 设置为 false 的成员是读/写的,并且可以更改。默认为否。

      System.ComponentModel.DataAnnotations.EditableAttribute
      

      https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.editableattribute%28v=vs.110%29.aspx

      指示数据字段是否可编辑。

      数据字段上存在 EditableAttribute 属性表明用户是否应该能够更改字段的值。 此类既不强制也不保证字段是可编辑的。无论此属性是否存在,底层数据存储都可能允许更改字段。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-13
        • 1970-01-01
        • 2010-09-21
        • 2011-10-03
        • 1970-01-01
        • 1970-01-01
        • 2021-07-26
        • 2023-04-03
        相关资源
        最近更新 更多