-2

PurchaseOrderModel.cs

public class PurchaseOrderModel {
    public SupplierModel Supplier { get; set; }
}

SupplierModel.cs

public class SupplierModel {
    public string Code { get; set; }
    public string Name { get; set; }

    public override string ToString() {
        return $"{Name} ({Code})";
    }
}

PurchseOrdersReport.cshtml

@Html.DisplayFor(purchaseOrder => purchaseOrder.Supplier)

I would like that the Razor engine calls the ToString() method of Supplier. But it doesn't, I got the following HTML output instead:

<div class="display-label">Code</div>
<div class="display-field">USSCIESTMI</div>
<div class="display-label">Name</div>
<div class="display-field">MY SUPPLIER NAME</div>
olivierr91
  • 1,243
  • 3
  • 13
  • 29
  • 1
    `DisplayNameFor()` uses the name of the property or the value of the `[Display(Name = "..")]` if present. Why not just use `@Model.Supplier.ToString()`? –  May 03 '18 at 03:23
  • `@Html.DisplayNameFor(purchaseOrder => purchaseOrder.Supplier)` will generate HTML markup with type name of `SupplierModel`. If you want `DisplayNameFor` to display formatted string, create a [display template](https://stackoverflow.com/questions/41490904/create-a-template-for-displaynamefor-method-in-asp-net-mvc) instead. – Tetsuya Yamamoto May 03 '18 at 03:31
  • And I assume you have a typo in your code, and you meant `@Html.DisplayFor()`, not `@Html.DisplayNameFor()` –  May 03 '18 at 03:45
  • @StephenMuecke indeed, I fixed the typo. And yes Model.Supplier.ToString() is what I use, I just wanted to be consistent with the rest of my stsatements, which all use Html.DisplayFor. Thanks for the answer – olivierr91 May 04 '18 at 14:49

2 Answers2

0

I found another topic at Stack overflow that outlines the following solution. Please refer How to show the model's attribute dynamically in mvc?

There is a overload for @Html.DisplayFor(...) that takes two args.

@Html.DisplayFor(purchaseOrder => purchaseOrder.Supplier, Model.Supplier.ToString())
Ashokan Sivapragasam
  • 2,033
  • 2
  • 18
  • 39
  • The 2nd parameter is the name of the `DisplayTemplate` - i.e. the name of a `.cshtml` file. This has nothing to do with OP's issue –  May 04 '18 at 01:01
0

Try using

@(Model.PropertyType.ToString())

Or simply

@Model.PropertyType

instead of @Html.DisplayFor