I want DRY/reuse as much editor code (View and Model) as possible. Some of my fields can only be set at creation, and never edited. Are there any pre-existing MVC/DataAnnotation features I should look at?
For example, maybe there is a data attribute that causes EditorFor to operate like DisplayFor if the value is non-null.
Model.cs
[Unchangeable]
string UserReferenceId { get; set; }
string Description { get; set; }
edit: to clarify my goal, I’ve added an answer with sample code for the approach I’m currently planning. If there’s a better way/pre-existing feature for this, please let me know.
There are both the
System.ComponentModel.ReadOnlyAttributeandSystem.ComponentModel.DataAnnotations.EditableAttribute(I thinkEditableAttributeis .NET 4). When model metadata is created for properties marked with either of these, you can seeModelMetadata.IsReadOnlywill be set correctly.Frustratingly, however, the built-in editor templates will still show editable fields, even if
ModelMetadata.IsReadOnlyistrue.You can, however, create your own shared editor template for each data type where you want this metadata property respected, and handle it specifically.
~/Views/Shared/EditorTemplates/String.cshtml
View Model
You’ll note that in the event the metadata for the model indicates IsReadOnly, I draw a hidden field. This is so the value of that property is persisted across posts.
If you don’t want the field displayed at all, but persisted across posts, you can use
System.Web.Mvc.HiddenInputAttribute. In this case, only the hidden is drawn.