Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Html.DisplayTextFor ignoring DisplayFormatAttribute?

I've read elsewhere that DisplayFormat just uses the DataFormatString in the same way string.Format does. I am trying to display a long as a phone number; in a console app, the following works:

const string PhoneFormat = "{0:###-###-####}";
long? phone = 8005551212;
string s = string.Format(PhoneFormat, phone);

s = "800-555-1212"

Why is it that when I use it in my view as

@Html.DisplayTextFor(model => model.Patient.Phone)

what is displayed is 8005551212

Here's the model...

public class Patient
{
    [DisplayFormat(DataFormatString = "{0:###-###-####}")]
    public long? Phone { get; set; }
}

Also tried DisplayFor, which also does not work.

The only way that seems to work for me is

Html.Raw(string.Format("{0:###-###-####}", Model.Patient.Phone))
like image 783
Paul Rivera Avatar asked Nov 23 '11 20:11

Paul Rivera


1 Answers

I had a quick look into the MVC3 source. I'm assuming you're specifying your format via DataAnnotations

[DisplayFormat(DataFormatString = "{0:###-###-####}")]
public long Phone { get; set; }

It looks like this is not applied when you use the @Html.DisplayTextFor(m => m.Property) helper which apparently ends up doing a simple ToString. It is however applied when you use @Html.DisplayFor(m => m.Property), which calls through the TemplateHelpers.

like image 56
David Ruttka Avatar answered Nov 04 '22 09:11

David Ruttka