maxspan maxspan - 3 years ago 131
ASP.NET (C#) Question

How to set controls visibility dynamically in MVC depending on database records

I am looking for setting my controls visible depending on the Database column visibility option set to true or false. I would like to set the controls visibility dynamically. I thinking of using CustomAttributes and setting the ViewModel with it. But I dont know how. A starting point from someone and help me to start.

[Visible]
public string FullName { get; set; }

Answer Source

Mine is slightly simpler than ali's answer:

In your Model class:

public class Client
{
    [Visible]
    public string FullName { get; set; }
}

Add an extension method 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);
        }
    }
}

Then in your view:

@Html.VisibleLabelFor(m => m.FullName)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download