MVC 3: Hide ID property with EditorForModel

I have this line in my view:

@Html.EditorForModel() 

And this is my ViewModel:

 public class CommentForm { public int Id { get; set; } [DisplayName("Kommentar"), DataType(DataType.MultilineText)] public string Comment { get; set; } } 

The problem is that Id displayed as a text field in the form. In fact, I want to use Id in form action. Is there an attribute that tells the editor not to display the Id property?

+4
source share
3 answers

Thank you for your contributions, but I really did not like them.

I made my own PreventRenderingAttribute.

PreventRenderingAttribute.cs

 [AttributeUsage(AttributeTargets.Property)] public class PreventRenderingAttribute : Attribute, IMetadataAware { public void OnMetadataCreated(ModelMetadata metadata) { metadata.ShowForDisplay = false; metadata.ShowForEdit = false; } } 

And in CommentForm

 [PreventRendering] public int Id { get; set; } 
+14
source

Setting ShowForDisplay and ShowForEdit to false is already performed by the standard

  [System.ComponentModel.DataAnnotations.ScaffoldColumn(false)] 

attribute. Therefore, your custom attribute seems redundant.

+20
source

One possibility is to display it as a hidden field:

 [HiddenInput(DisplayValue = false)] public int Id { get; set; } 

Another possibility is to write a custom editor template for your CommentForm view CommentForm , and inside this template include everything you want ( ~/Views/Shared/EditorTemplates/CommentForm.cshtml ):

 @model CommentForm <div> @Html.EditorFor(x => x.Comment) </div> 
+15
source

Source: https://habr.com/ru/post/1384075/


All Articles