C#ExpressiveAnnotations当需要字段时如何添加星号符号

C#ExpressiveAnnotations当需要字段时如何添加星号符号,c#,expressiveannotations,C#,Expressiveannotations,非常好的图书馆: 但我不知道在需要字段时如何添加星号符号。这可能吗。如果是,怎么做 代码 我尝试: var metaData = ModelMetadata.FromLambdaExpression(expression, html.ViewData); var isRequired = metaData.ContainerType.GetProperty(metaData.PropertyName).GetCustomAttributes(typeof(RequiredIfAttribute

非常好的图书馆:

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

代码

我尝试:

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

但是总是
正确的
什么是错误的

您可以在属性上使用DataAnnotation来获得稍微不同的效果:

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(此HtmlHelper html,表达式)
{
if(ModelMetadata.FromLambdaExpression(expression,html.ViewData).IsRequired)
返回“*”;
其他的
返回字符串。空;
}

Thx表示提示,但RequiredMarkFor方法在我的示例中始终为false。我使用的是ExpressiveAnnotations库,而不是简单的必填字段
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;
}