【问题标题】:C# ExpressiveAnnotations how to add Asterisk notation when field is requiedC#ExpressiveAnnotations如何在需要字段时添加星号表示法
【发布时间】:2015-10-23 17:31:40
【问题描述】:

非常好的库: https://github.com/jwaliszko/ExpressiveAnnotations

但我不知道如何在需要字段时添加星号符号。这可能吗。如果是怎么办?

代码

[RequiredIf("IsCustomerInputRequired == true")]
[Display(Name = Translations.Global.USER)]
public string CustomerInput { get; set; }

我尝试:

var metaData = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
var isRequired = metaData.ContainerType.GetProperty(metaData.PropertyName).GetCustomAttributes(typeof(RequiredIfAttribute), false).Any();

但总是true怎么了

【问题讨论】:

    标签: c# expressiveannotations


    【解决方案1】:

    您可以在属性上使用 DataAnnotations 以获得稍微不同的所需效果:

    using System.ComponentModel.DataAnnotations;
    
    [Required(ErrorMessage="[Education] Please enter the University of Institution.")]
    public string School
    {
        get { return _school; }
        set { _school = value; OnPropertyChanged();}
    }
    

    或者您可以尝试自己的 HtmlHelper 扩展:

    public static string RequiredMarkFor<TModel, TValue>(this HtmlHelper html,     Expression<Func<TModel, TValue>> expression)
    {
        if(ModelMetadata.FromLambdaExpression(expression,  html.ViewData).IsRequired)
             return "*";
        else
             return string.Empty;
    }
    

    【讨论】:

    • 感谢提示,但在我的示例中,RequiredMarkFor 方法总是错误的。我使用的是 ExpressiveAnnotations 库而不是简单的必填字段
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 2019-10-28
    • 2011-06-03
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多