Call DisplayFormatAttribute's Logic from C#

本文关键字:Logic from DisplayFormatAttribute Call | 更新日期: 2023-09-27 18:16:42

在我的MVC5应用程序中,我在模型的属性上设置了这个DisplayFormat属性。它确保我的双值'TotalPrice'总是在屏幕上呈现两个小数点(在Razor页面中)

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

我正试图找出如何从我的控制器(c#代码)内调用相同的逻辑。比如:

返回DataFormatAttribute.ApplyFormattingTo (shoppingCart.TotalPrice);

这显然是不正确的,但我希望它有助于澄清问题。我对小数点后2位的具体例子并不感兴趣,我更感兴趣的是如何在c#中自己将属性的行为应用于值。

我已经下载了MVC5的源代码,但是它对我来说太抽象了,我无法理解。

谢谢你的帮助。

Call DisplayFormatAttribute's Logic from C#

我不确定它是否可用OOB,但看起来你需要阅读Attribute并应用你的格式。编写一个扩展方法,该方法将基于DisplayFormatAttribute DataFormatString属性应用格式化。

我希望这个例子能让你开始,即使它不是一个确切的解决方案。此示例仅与DisplayFormatAttribute紧密结合
    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 "";
    }
使用

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

实际实现根据您的需求而有所不同。

@Searching提供了答案,所以这只是我的最终代码,以防将来对其他人有所帮助。CartExtension类为Cart类提供扩展方法。

namespace MyApp.Models
{
    public static class CartExtension
    {
        /// <summary>
        /// Apply the formatting defined by the DisplayFormatAttribute on one of the Cart object's properties
        /// programatically. Useful if the property is being rendered on screen, but not via the usual Html.DisplayFor
        /// method (e.g. via Javascript or some other method)
        /// </summary>
        /// <param name="cart"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public static string ApplyFormattingTo(this Cart cart, string propertyName)
        {
            var property = cart.GetType().GetProperty(propertyName);
            var attriCheck = property.GetCustomAttributes(typeof(DisplayFormatAttribute), false);
            if (attriCheck.Any())
            {
                return string.Format(((DisplayFormatAttribute)attriCheck.First()).DataFormatString, property.GetValue(cart, null));
            }
            return "";
        }
    }
}

这可以用来返回预格式化的屏幕值,例如在Controller方法中:

return Json(cart.ApplyFormattingTo("TotalPrice"));