我想根据数据库列可见性选项设置为true或false来设置控件的可见性。我想动态设置控件的可见性。我想使用CustomAttributes并用它设置ViewModel。但我不知道怎么做。一个起点从某人和帮助我开始。
[Visible]
public string FullName { get; set; }
我的答案比ali的答案略简单:
在您的模型类中:
public class Client
{
[Visible]
public string FullName { get; set; }
}
添加扩展方法VisibleLabelFor
public static class HtmlExtensions
{
public static MvcHtmlString VisibleLabelFor<TModel, TResult>(this HtmlHelper<TModel> html, Expression<Func<TModel, TResult>> expression)
{
var type = expression.Body.NodeType;
if (type == ExpressionType.MemberAccess)
{
var memberExpression = (MemberExpression) expression.Body;
var p = memberExpression.Member as PropertyInfo;
if (!Attribute.IsDefined(p, typeof (VisibleAttribute)))
return new MvcHtmlString(string.Empty);
return html.LabelFor(expression);
}
}
}
那么在你看来:
@Html.VisibleLabelFor(m => m.FullName)
您可以用Razor编写一个简单的@helper,如下所示:
在App_CodeMyHelpers.cshtml
:中
@helper DisplayIt(object value, bool visibility)
{
if (!visibility){return;}
<span>@value</span>
}
然后在你的视图中这样使用它:
@MyHelpers.DisplayIt(@Model.FullName, @Model.Visible)
@MyHelpers.DisplayIt(@Model.Email, @Model.Visible)
@MyHelpers.DisplayIt(@Model.Tel, @Model.Visible)
您必须执行以下步骤:
步骤1:创建自定义属性
public class VisibilityAttribute : ValidationAttribute
{
private bool _isVisible;
public VisibilityAttribute(bool visible = true)
{
_isVisible = visible;
}
public bool Status
{
get
{
return _isVisible;
}
set
{
_isVisible = value;
}
}
}
步骤2:将自定义属性添加到模型
[Visibility(Status = false)]
public string FullName { get; set; }
步骤3:创建自定义Html帮助程序
public static class CustomHtmlExtensions
{
public static MvcHtmlString CustomDisplayFor<TModel, TResult>(this HtmlHelper<TModel> html,
Expression<Func<TModel, TResult>> expression)
{
ExpressionType type = expression.Body.NodeType;
if (type == ExpressionType.MemberAccess)
{
MemberExpression memberExpression = (MemberExpression)expression.Body;
PropertyInfo pi = memberExpression.Member as PropertyInfo;
var attributes = pi.GetCustomAttributes();
foreach (var attribute in attributes)
{
if (attribute is VisibilityAttribute)
{
VisibilityAttribute vi = attribute as VisibilityAttribute;
if (vi.Status)
{
var metadata = ModelMetadata.FromLambdaExpression<TModel, TResult>(expression, html.ViewData);
return MvcHtmlString.Create(metadata.SimpleDisplayText);
}
}
}
}
return MvcHtmlString.Create("");
}
}
步骤4:在视图中使用自定义Html Helper
@Html.CustomDisplayFor(model => model.FullName)