Bridget the Midget
Bridget the Midget

Reputation: 842

MVC 3: Hide ID property using 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 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

Answers (3)

Georg Patscheider
Georg Patscheider

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

Bridget the Midget
Bridget the Midget

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

Darin Dimitrov
Darin Dimitrov

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

Related Questions