【问题标题】:Using Data Annotations to check for a specific value使用数据注释检查特定值
【发布时间】:2012-07-30 22:16:50
【问题描述】:

我的数据模型中有以下属性:

[Required]
[DataType(DataType.Text)]
[Display(Name = "First Name")]
public string FirstName { get; set; }

[Required]
[DataType(DataType.Text)]
[Display(Name = "Last Name")]
public string LastName { get; set; }

我的文本框目前有一个占位符,因此当他们专注于文本框时,占位符将消失在文本框中,如果他们不输入任何内容,则文本框 val ($(textbox).val()) 等于“名字”或“姓氏”,如果FirstNameLastName 等于“名字”和“姓氏”

【问题讨论】:

标签: c# jquery asp.net asp.net-mvc-3


【解决方案1】:

您应该编写自己的 ValidationAttribute 并将其用于您的属性

简单示例:

public sealed class PlaceHolderAttribute:ValidationAttribute
{
    private readonly string _placeholderValue;

    public override bool IsValid(object value)
    {
        var stringValue = value.ToString();
        if (stringValue == _placeholderValue)
        {
            ErrorMessage = string.Format("Please fill out {0}", _placeholderValue);
            return false;
        }
        return true;
    }

    public PlaceHolderAttribute(string placeholderValue)
    {
        _placeholderValue = placeholderValue;
    }
}

像这样在您的财产上使用它:

[Required]
[DataType(DataType.Text)]
[Display(Name = "First Name")]
[PlaceHolder("First Name")]
public string FirstName { get; set; }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 1970-01-01
    相关资源
    最近更新 更多