I have a viewmodel that has an int StateID
field and a string StateName
field like so:
public class DepartmentViewModel : BaseViewModel, IModelWithId
{
// only show in edit mode
public int StateId { get; set; }
// only show in display mode
public string StateName { get; set; }
}
I have a read only view that uses DisplayForModel
and an update view that uses EditorForModel
. I want the DisplayForModel
view to show the StateName
property, and the EditorForModel
view use the StateID
property (I am actually rendering a dropdownlist based on this).
I have not been able to figure out how to decorate my viewmodel properties to create this behavior.
A comment on CodeGrue's answer.
Make the attribute inherit IMetadataAware instead. That way you don't need to build your own DataAnnotationsModelMetadataProvider.
The new attribute would become something like:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class RenderModeAttribute : Attribute, IMetadataAware
{
public RenderMode RenderMode { get; set; }
public RenderModeAttribute(RenderMode renderMode)
{
RenderMode = renderMode;
}
public void OnMetadataCreated(ModelMetadata metadata)
{
switch (RenderMode)
{
case RenderMode.DisplayModeOnly:
metadata.ShowForDisplay = true;
metadata.ShowForEdit = false;
break;
case RenderMode.EditModeOnly:
metadata.ShowForDisplay = false;
metadata.ShowForEdit = true;
break;
case RenderMode.None:
metadata.ShowForDisplay = false;
metadata.ShowForEdit = false;
break;
}
}
}
public enum RenderMode
{
Any,
EditModeOnly,
DisplayModeOnly
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With