我有一个MVC4项目,我想在其中使用类似于DisplayFromat的功能,但是设置DataFormatString是不够的。我希望调用一个函数来格式化字符串。这有可能吗?
我已经测试了继承DisplayFormat,但这只是让我设置DataFormatString。
我已经研究过自定义DataAnnotationsModelMetadataProvider,但我不知道如何让它调用自定义函数进行格式化。
我的特殊情况是,我需要将整数201351格式化为"w51 201351“。我想不出一个能做到这一点的格式字符串。
发布于 2013-05-13 21:33:56
最简单的方法是在Model上公开一个只读属性:
public class Model{
public int mydata{get; set;}
public string formattedDate{
get{
string formattedval;
// format here
return formattedval;
};
}
}发布于 2014-02-25 01:28:04
您可以创建自定义ValidationAttribute。下面是我用来验证是否有人选择了下拉值的一些代码。
using System.ComponentModel.DataAnnotations;
public sealed class PleaseSelectAttribute : ValidationAttribute
{
private readonly string _placeholderValue;
public override bool IsValid(object value)
{
var stringValue = value.ToString();
if (stringValue == _placeholderValue || stringValue == "-1")
{
ErrorMessage = string.Format("The {0} field is required.", _placeholderValue);
return false;
}
return true;
}
public PleaseSelectAttribute(string placeholderValue)
{
_placeholderValue = placeholderValue;
}
}然后使用它:
[Required]
[Display(Name = "Customer")]
[PleaseSelect("Customer")]
public int CustomerId { get; set; }https://stackoverflow.com/questions/16523237
复制相似问题