Richard Richard - 9 months ago 61
C# Question

Call DisplayFormatAttribute's Logic from C#

In My MVC5 application, I have this DisplayFormat attribute set on a property of my model. It ensures that my double value 'TotalPrice' is always rendered with two decimal places on the screen (in a Razor page)

[DisplayFormat(DataFormatString = "{0:N2}")]
public Double? TotalPrice { get; set; }

I'm trying to figure out how to call the same logic from within my Controller (C# code). So something like:

return DataFormatAttribute.ApplyFormattingTo(shoppingCart.TotalPrice);

That's obviously nowhere near correct but I hope it helps to clarify the question. I'm not really interested in the specific example of 2 decimal places, more how to apply an attribute's behaviour to a value by myself in C#.

I've downloaded the MVC5 source code, but it's all a bit too abstract for me to get my head around.

Thanks for any help you can give.

Answer Source

I'm not sure if its available OOB but it looks like you need to read the Attribute and apply your formatting. Write an extension method that will apply the formatting based on the DisplayFormatAttribute DataFormatString property.

I hope this sample gets you started, even if it's not an exact solution. This sample is tightly bound to DisplayFormatAttribute only

    public static string ApplyFormattingTo(this object myObject, string propertyName) 
        var property = myObject.GetType().GetProperty(propertyName);        
        var attriCheck = property.GetCustomAttributes(typeof(DisplayFormatAttribute), false); 
             return string.Format(((DisplayFormatAttribute)attriCheck.First()).DataFormatString,property.GetValue(myObject, null)); 
        return "";


Cart model= new Cart();
model.amount = 200.5099;    
var formattedString = pp.ApplyFormattingTo("amount");

Actual implementation varies according to your requirement. Hope it helps.