MVC controlling which properties are shown with DisplayFor?

476 Views Asked by At

I'm using MVC's DisplayFor method to show the value of a property. However, if this value is yet another Model-object, then it will include the "ID" property of that object. I don't like that, and showing the internal database ID is not nescessary in my application.

Can I (through annotations or something similar) mark this property as "not included" in the DisplayFor process?

1

There are 1 best solutions below

0
On BEST ANSWER

You might not be taking advantage of what DisplayFor can do:

<%=Html.DisplayFor(m => m.Property) %>

and let's say that Property is of type User

Now you can create a DisplayTemplate (~/Views/Shared/DisplayTemplates/User.ascx) that is strongly typed to User and also named User.ascx. And since Property is a User, MVC will bind this object to this User DisplayTemplate.

Which could look like this:

<%@ Control Language="C#" Inherits="ViewUserControl<User>" %>
<h2><%=Model.Name %></h2>
<strong><%=Model.Email %></strong>

Now you can show/ hide whatever you want off of the object your passing to DisplayFor