Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mark a field "Read Only" with Data Annotations

I am trying to make the ID field read only. It is an Identity field in the DB so the user will not be setting it. However they would like to see it. What am I missing as the below, when assigned to a DataForm still allows that value to be Edited.

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();
        }
    }
}
like image 242
Refracted Paladin Avatar asked May 09 '13 05:05

Refracted Paladin


2 Answers

Mark Property with ReadOnly attribute.

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

Follow below link for more Has the behavior for DataAnnotations in asp.net mvc 3 changed?

like image 58
vijay Avatar answered Nov 09 '22 17:11

vijay


You have two options in general based on situation.

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

Below are descriptions from MSDN

System.ComponentModel.ReadOnlyAttribute

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

Specifies whether the property this attribute is bound to is read-only or read/write. Members that are marked with the ReadOnlyAttribute set to true or that do not have a Set method cannot be changed. Members that do not have this attribute or that are marked with the ReadOnlyAttribute set to false are read/write, and they can be changed. The default is No.

System.ComponentModel.DataAnnotations.EditableAttribute

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

Indicates whether a data field is editable.

The presence of the EditableAttribute attribute on a data field indicates whether the user should be able to change the field's value. This class neither enforces nor guarantees that a field is editable. The underlying data store might allow the field to be changed regardless of the presence of this attribute.

like image 7
Tejasvi Hegde Avatar answered Nov 09 '22 17:11

Tejasvi Hegde