c# - 在视图模型中有条件地更改显示名称
问题描述
我是 Razor 和 View Models 的新手,我只想问是否可以在其中显示不同的字符串[Display(Name = "")]
我尝试在 Display 和变量之间添加条件,但它显示错误
也试过这个
public string Color {get;set;}
public String ColorDisplay
{
get
{
String name = "";
if (ColorId == 25 || ColorId == 26)
{
name = "Purple";
}
else
{
name = "Green";
}
return name;
}
}
然后在我看来
@Html.LabelFor(m => m.ColorDisplay)
但似乎不起作用,因为它只是显示ColorDisplay
解决方案
在这个问题中,您可能需要一个自定义属性来根据属性属性中提供的值更改文本。假设您想要这样的自定义属性用法:
[DisplayWhen("ColorId", 25, 26, "Purple", "Green")]
public String Color { get; set; }
并像这样使用 HTML 助手:
@Html.LabelFor(m => m.Color)
然后你应该执行以下步骤:
1)创建从Attribute
类继承的自定义属性。
public class DisplayWhenAttribute : Attribute
{
private string _propertyName;
private int _condition1;
private int _condition2;
private string _trueValue;
private string _falseValue;
public string PropertyName
{
get
{
return _propertyName;
}
}
public int Condition1
{
get
{
return _condition1;
}
}
public int Condition2
{
get
{
return _condition2;
}
}
public string TrueValue
{
get
{
return _trueValue;
}
}
public string FalseValue
{
get
{
return _falseValue;
}
}
public DisplayWhenAttribute(string propertyName, int condition1, int condition2, string trueValue, string falseValue)
{
_propertyName = propertyName;
_condition1 = condition1;
_condition2 = condition2;
_trueValue = trueValue;
_falseValue = falseValue;
}
}
2) 创建自定义元数据提供程序类,检查自定义属性是否存在。
public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
{
var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
var additionalAttribute = attributes.OfType<DisplayWhenAttribute>().FirstOrDefault();
if (additionalAttribute != null)
{
metadata.AdditionalValues.Add("DisplayWhenAttribute", additionalValues);
}
return metadata;
}
}
3) 像这样注册CustomModelMetadataProvider
到Application_Start()
Global.asax 中的方法中:
protected void Application_Start()
{
ModelMetadataProviders.Current = new CustomModelMetadataProvider();
}
4)创建您自己的(或覆盖现有的)LabelFor
助手,以便它检查DisplayWhenAttribute
,如下例所示:
public static MvcHtmlString LabelFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
{
string result = string.Empty;
var modelMetaData = expression.Compile().Invoke(helper.ViewData.Model);
string fieldName = ExpressionHelper.GetExpressionText(expression);
var containerType = typeof(TModel);
var containerProperties = containerType.GetProperties();
var propertyInfo = containerProperties.SingleOrDefault(x => x.Name == modelMetaData.PropertyName);
var attribute = propertyInfo.GetCustomAttributes(false).SingleOrDefault(x => x is DisplayWhenAttribute) as DisplayWhenAttribute;
var target = attribute.PropertyName; // target property name, e.g. ColorId
var condition1 = attribute.Condition1; // first value to check
var condition2 = attribute.Condition2; // second value to check
var targetValue = (int)containerType.GetProperty(target).GetValue(helper.ViewData.Model);
// checking provided values from attribute
if (targetValue == condition1 || targetValue == condition2)
{
result = attribute.TrueValue;
}
else
{
result = attribute.FalseValue;
}
// create <label> tag with specified true/false value
TagBuilder tag = new TagBuilder("label");
tag.MergeAttributes(htmlAttributes);
tag.Attributes.Add("for", helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(fieldName));
tag.SetInnerText(result);
return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
}
需要考虑的一些参考资料:
推荐阅读
- retrofit2 - Retrofit2:如何向服务器发送javaBean数据?(这个JavaBean中有很多文件)
- elasticsearch - Elasticsearch - 在 Multi Get Java API 中使用通配符
- r - 更改 R 中动态选择列表的值
- sql - SQL Server 中的空格是否占用字符数
- ios - 如何快速制作 DatagramPacket 代码?
- spring - hibernate 的 Propagation.REQUIRES_NEW 会解决数据库表锁定问题吗?
- sql - SQL如何获取创建列的平均值
- vim - Vim 用相同的格式字符串替换字符串但名称不同
- c - 如何将子进程的返回值返回给使用 exec 创建的父进程?
- javascript - javascript项目的firebase初始化代码是否需要在每个网页上运行?