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.DataAnnot
Found that the use of Editable instead Readonly on the model works exactly the same.
[ReadOnly(true)] //or
[Editable(false)]
public string Name { get; set; }
This syntax does work when interrogating a property attribute on the view itself. Also works when attribute is Editable(true)
@if (ViewData.ModelMetadata.Properties.Where(p => p.PropertyName == "Name").First().IsReadOnly)
{
@Html.TextBoxFor(model => model.Name, new { style = "width:190px; background-color: #ffffd6", @readonly = "readonly" })
}
else
{
@Html.TextBoxFor(model => model.Name, new { style = "width:190px; " })
}
Using an editor template here a simple string template:
@model String
@{
IDictionary htmlAttributes = new Dictionary();
if (ViewData.ModelMetadata.IsReadOnly) //this will be looking at the actual property not the complete model
{
htmlAttributes.Add("style", "width:100px; background-color:#ffffd6");
htmlAttributes.Add("readonly", "readonly");
@Html.TextBox("", Model, htmlAttributes)
}