asp.net mvc 5 - Call DisplayFormatAttribute's Logic from C# -


in mvc5 application, have displayformat attribute set on property of model. ensures double value 'totalprice' rendered 2 decimal places on screen (in razor page)

[displayformat(dataformatstring = "{0:n2}")] public double? totalprice { get; set; } 

i'm trying figure out how call same logic within controller (c# code). like:

return dataformatattribute.applyformattingto(shoppingcart.totalprice);

that's near correct hope helps clarify question. i'm not interested in specific example of 2 decimal places, more how apply attribute's behaviour value myself in c#.

i've downloaded mvc5 source code, it's bit abstract me head around.

thanks can give.

i'm not sure if available oob looks need read attribute , apply formatting. write extension method apply formatting based on displayformatattribute dataformatstring property.

i hope sample gets started, if it's not exact solution. sample tightly bound displayformatattribute only

    public static string applyformattingto(this object myobject, string propertyname)      {         var property = myobject.gettype().getproperty(propertyname);                 var attricheck = property.getcustomattributes(typeof(displayformatattribute), false);          if(attricheck.any())         {                 return string.format(((displayformatattribute)attricheck.first()).dataformatstring,property.getvalue(myobject, null));          }         return "";     } 

usage

cart model= new cart(); model.amount = 200.5099;     var formattedstring = pp.applyformattingto("amount"); 

actual implementation varies according requirement. hope helps.


Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -