Search code examples
asp.net-mvcrazormodelcustom-formatting

ASP.NET MVC4 custom formatting method for Model


 <div>
Email: 
<a id="email href="mailto:@Model.Contact.Email">@Model.Contact.Email.ToStringMyCustomFormatted</a>
</div>

I want to create custom method for formatting and apply it like this. (in the same way we can apply ToString() method to this.) I don't want to use JavaScript to do any formatting by using Document.Ready(). In short I want to extend ToString method something like ToStringMyCustomFormatted, by which I can apply my own rules to string output. I am not even sure if something like can be done. Please Enlighten !


Solution

  • You could use a simple C# extension method (or directly on your Contact model):

    public static class YourContactModelExtensions {
        public static string ToStringMyCustomFormat(this YourContactModel m) {
            // TODO
        }
    } 
    

    or if you wanted it to apply to all strings:

    public static class StringExtensions {
        public static string ToMyCustomFormat(this string s) {
            // TODO
        }
    } 
    

    or a Razor helper function on your Razor page:

    @helper ToStringMyCustomFormat(YourContactModel m) {
       @* TODO *@
    }
    

    or

    @helper ToMyCustomFormat(string s) {
       @* TODO *@
    }