0

In have a typed view of :

@model modelLib.Client

But further down the code I want the DisplayNameFor of a property for another model, precisely the modelLib.Licence model.

Normally, for the typed model I would do :

@Html.DisplayNameFor(model => model.prop) // Client

Any ideas ?

Mehdiway
  • 10,337
  • 8
  • 36
  • 68
  • You should use Reflection to get attributes data. Can you say What attribute to you use? `DisplayName` or `Display` abouve your model property? – teo van kot Jul 13 '15 at 14:37
  • Is there any relation between `Client` and `License`? That is, somewhere in the property hierarchy of the `Client` object is there a `License` object? If so, you can navigate to that: `@Html.DisplayNameFor(model => model.SomeLicense.SomeProperty)` – David Jul 13 '15 at 14:39
  • @teovankot `modelLib.Licence` has 2 properties `Name` and `End`, each with `[Display(Name = "Something")]` – Mehdiway Jul 13 '15 at 14:39
  • @David Yes there is, but it's a collection – Mehdiway Jul 13 '15 at 14:40
  • 1
    i gess [this is the answer](http://stackoverflow.com/a/5475513/1849444) you're looking for – teo van kot Jul 13 '15 at 14:45

1 Answers1

3

(In response to comments above...)

Just use the property on the nested model. For a single instance, it would be something like this:

@Html.DisplayNameFor(model => model.SomeLicense.SomeProperty)

For a collection of instances, where the parent model has a collection of the nested model, you can refer to an instance in the collection:

@Html.DisplayNameFor(model => model.SomeLicenses.First().SomeProperty)

It may appear that the call to First() could fail in the event that there are zero elements, but it never actually invokes First() in this case. The reference itself is just used by the framework for what I might call "some reflection trickery" to get type information so it can reference the attributes on that property.

David
  • 208,112
  • 36
  • 198
  • 279