Search code examples
asp.net-mvc-3display-templates

How to exclude a field from @Html.EditForModel() but have it show using Html.DisplayForModel()


I am reading up on ASP.NET MVC and all of it's fun uses and I just found out about DataTemplates.

In my hurry to test this thing out, I converted one of my simpler models over to using @Html.DisplayForModel() and @Html.EditForModel() and it worked like a lucky charm that it is :)

One thing that I immediately found out though was that I could not easily define a field to show up on display views but not be present at all for editing...


Solution

  • You can make use of IMetadataAware interface an create attribute which will set ShowForEdit and ShowForDislay in Metadata:

    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class TemplatesVisibilityAttribute : Attribute, IMetadataAware
    {
        public bool ShowForDisplay { get; set; }
    
        public bool ShowForEdit { get; set; }
    
        public TemplatesVisibilityAttribut()
        {
            this.ShowForDisplay = true;
            this.ShowForEdit = true;
        }
    
        public void OnMetadataCreated(ModelMetadata metadata)
        {
            if (metadata == null)
            {
                throw new ArgumentNullException("metadata");
            }
    
            metadata.ShowForDisplay = this.ShowForDisplay;
            metadata.ShowForEdit = this.ShowForEdit;
        }
    
    }
    

    Then you can attach it to your property like this:

    public class TemplateViewModel
    {
      [TemplatesVisibility(ShowForEdit = false)]
      public string ShowForDisplayProperty { get; set; }
    
      public string ShowAlwaysProperty { get; set; }
    }
    

    And this is all you need.