12

While the toot-tip says,

enter image description here

I tried using it but could not make it to work. I am not sure how it works and about its functionality. So what purpose does this built-in attribute ReadOnlyserve?

Any inputs will be appreciated. Thank you.

Aritra B
  • 1,726
  • 6
  • 29
  • 45

2 Answers2

18

I assume you use this property in a view with something like EditorFor? Then use:

[Editable(false)]
public string MyProperty {get;set;}

or

@Html.TextBoxFor(x => x.MyProperty, new { readonly = "readonly" })

If you want a readonly public property of a class use:

public string MyProperty {get; private set;}
Marthijn
  • 3,292
  • 2
  • 31
  • 48
  • Thank you for the post. I got your point, but what I am curious about is the use of this attribute on the model properties. – Aritra B Dec 13 '13 at 12:41
  • I think the readonly attribute is just used as metadata for reflection, and not by the MVC EditorFor. More info here: http://msdn.microsoft.com/en-us/library/system.componentmodel.readonlyattribute.aspx Here is a solution for a working readonly attribute: http://stackoverflow.com/questions/18515441/mvc-4-razor-data-annotations-readonly – Marthijn Dec 13 '13 at 12:45
  • 1
    @Html.TextBoxFor(x => x.MyProperty, new { @readonly = true }) this is also working – unique Dec 13 '13 at 12:57
  • @Marthijn Thanks for the links.Actually, I am searching for the purposes that this attribute fulfills when used on model properties. Reflection, definitely can be one of the reasons. Thanks. – Aritra B Dec 13 '13 at 13:01
1
@Html.EditorFor(
  model => model.id_to_fetch,
  new {
    htmlAttributes = new {
      @class = "form-control" , @readonly = "readonly"
    }
  }
)
Igor F.
  • 2,649
  • 2
  • 31
  • 39