I'm looking to use attributes to mark view model properties as readonly so that the view fields are read only in the rendered view. Applying System.ComponentModel.DataAnnotations.EditableAttribute appears to be the exact attribute I need but it does not appear to work i.e. textbox fields are still editable. I've looked all around and can find no answers and only a few related questions. The editable attribute as applied below does not work when the view is rendered.
[Display(Name = "Last Name")]
[Editable(false, AllowInitialValue = true)]
public string LastName { get; set; }
I can achieve the readonly behaviour using a view helper function like this but my preference is to use an attribute on the model property.
@functions {
object getHtmlAttributes()
{
if (@ViewBag.Mode == "Edit")
{
return new {style = "width:100px;background:#ff6;", @readonly = "readonly"};
}
return new { style = "width:100px;" };
}
}
@Html.TextBoxFor(model => model.FirstName, getHtmlAttributes())
Other attributes work perfectly ok including custom validation attributes. Can you tell me if the data annotations editable attribute works in this context, should just work as applied above or is there something else that needs to be done? Thanks.