displayformatattribute to custom format a string

断了今生、忘了曾经 提交于 2019-12-11 09:41:38

问题


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:


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.



来源:https://stackoverflow.com/questions/23778661/displayformatattribute-to-custom-format-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!