-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>
4
  • 1
    DisplayNameFor() uses the name of the property or the value of the [Display(Name = "..")] if present. Why not just use @Model.Supplier.ToString()?
    – user3559349
    May 3, 2018 at 3: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 instead. May 3, 2018 at 3:31
  • And I assume you have a typo in your code, and you meant @Html.DisplayFor(), not @Html.DisplayNameFor()
    – user3559349
    May 3, 2018 at 3: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 4, 2018 at 14:49

2 Answers 2

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())
1
  • 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
    – user3559349
    May 4, 2018 at 1:01
0

Try using

@(Model.PropertyType.ToString())

Or simply

@Model.PropertyType

instead of @Html.DisplayFor

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.