1

If you've defined a custom DisplayTemplate, is there some way to use the DisplayFormat.DataFormatString defined for that object?

For example, I've defined a DisplayTemplate for Double:

<div class="form-group">
    @Html.Label("", ViewData["label"] as string, new { @class = "col-sm-6" })
    <p class="col-sm-6">
        @Html.DisplayTextFor(m => m)
    </p>
</div>

Then my model defines a DisplayFormat:

[Display(Name = "In Weight")]
[DisplayFormat(DataFormatString = "{0} lb")]
public double? InWeight{ get; set; }

In the above example, DisplayTextFor only provides a simple ToString(), while replacing it with DisplayFor renders nothing.

2
  • Why are you using @Html.Label() when you do not have an associated form control. The reason DisplayFor() would not work is that it would keep calling itself. You could access the properties ModelMetadata to generate the formatted value Commented Jun 6, 2016 at 23:57
  • @StephenMuecke You're right, it's probably more appropriate to use a dl description list in this case, but the question would be the same for formatting the value. Commented Jun 7, 2016 at 0:01

1 Answer 1

3

The @Html.DisplayTextFor(m => m) method does not take into account the DisplayFormatAttribute and @Html.DisplayFor(m => m) does not work because it would be recursively calling itself creating an endless loop. You need to access the properties ModelMetadata.

Note also you are not generating a form control, so use of a <label> element would not be appropriate.

Your template should look something like

@model System.Double
<div>
    <div>@ViewData.ModelMetadata.GetDisplayName()</div>
    <div>@string.Format(ViewData.ModelMetadata.DisplayFormatString ?? "{0:0.00}", Model)</div>
</div>

and add class names to the enclosing elements to style it

Note I have added a 'default' format for properties where the [DisplayFormat] may not be applied.

Side note: Since the property is nullable, you could also enhance this further by including something like

@if (Model == null)
{
    <div>@(ViewData.ModelMetadata.NullDisplayText ?? "Not assigned")</div>
}
else
{
    <div>@string.Format(ViewData.ModelMetadata.DisplayFormatString ?? "{0:0.00}", Model)</div>
}
Sign up to request clarification or add additional context in comments.

1 Comment

I could never get string.format working for me here, had to end up going with DateValue.ToString(ViewData.ModelMetadata.DisplayFormatString); Although granted, I was working with an individual property.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.