Reputation: 842
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
renders as a textfield in the form. Actually, I only want to use Id
in the form action. Is there an attribute that tells the editor not to render the property Id
?
Upvotes: 4
Views: 9494
Reputation: 9463
Setting ShowForDisplay and ShowForEdit to false is already done by the standard
[System.ComponentModel.DataAnnotations.ScaffoldColumn(false)]
attribute. Your custom attribute therefore seems like overkill.
Upvotes: 21
Reputation: 842
Thanks for your contributions, but I didn't really 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; }
Upvotes: 14
Reputation: 1038810
One possibility is to render 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 model and inside this template include whatever you want (~/Views/Shared/EditorTemplates/CommentForm.cshtml
):
@model CommentForm
<div>
@Html.EditorFor(x => x.Comment)
</div>
Upvotes: 15