displayformatattribute to custom format a string

3.1k views Asked by At

I want to be able to mark properties in my viewmodel to be formatted using a custom format when displayed in my MVC view.

I assume I need my own displayformatattribute and set the displayformat but I am not sure how to set this displayformat or where. If I want to show a number as currency it is easy, just set DataFormatString to "{0:C}" in the constructor of the attribute.

But if for example I want to mask email addresses (so remove the domain name), how would I do this using either a displayformatattribute or maybe a datatypeattribute? So it is a string field that I want to transform. I know there are other approaches e.g. custom display templates but then I would lose some of the inbuilt htmlhelper functionality. I just want to change the format of the string nothing else. And preferably make it as simple as adding an attribute to those fields that need masking

The DataFormatString doesn't seem to be able to take a custom formatter?

cheers Phil

1

There are 1 answers

0
OzBob On

Somewhate similar to : How to make configurable DisplayFormat attribute

public class CustomDisplayFormatAttribute : DisplayFormatAttribute {
    public CustomDisplayFormatAttribute() {
        //MSDN Custom Date Format string rules:http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
        DataFormatString = "{0;dddd dd MMMM YYYY}";
    }
}

Then you can use it and the base attributes e.g. ApplyFormatInEditMode, as so:

[CustomDisplayFormatAttribute(ApplyFormatInEditMode = false)]
public DateTime? CreatedOn { get; set; }

Note for dates there is a server vs client Culture setting, http://msdn.microsoft.com/en-us/library/bb882561(v=vs.110).aspx discusses (but doesn't answer) how to do this in javascript.