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>
DisplayNameFor()uses the name of the property or the value of the[Display(Name = "..")]if present. Why not just use@Model.Supplier.ToString()?@Html.DisplayNameFor(purchaseOrder => purchaseOrder.Supplier)will generate HTML markup with type name ofSupplierModel. If you wantDisplayNameForto display formatted string, create a display template instead.@Html.DisplayFor(), not@Html.DisplayNameFor()