Question

I need to either mark controls as read-only, disable them or hide them entirely depending on various business rules.

Currently, I am passing an enum along for each property in my view model. I then check the value of enum for each control. This has led to a pretty nasty chunk of Razor. Even with @helpers the output is pretty nasty.

I am wondering if there is a better way to alter the appearance of a control based on business rules. Most of the time, I am just adding attributes. In the worst case, I am not displaying a control at all.

Was it helpful?

Solution

Display logic/responsibility falls on view's shoulders, so...

If rules are dependent on e.g. user permission and are applicable to all of the controls then I'd say one enum per viewmodel would be enough.

Otherwise your're doing it ok. The only thing I would change is I would write custom extension methods for displaying viewmodel properties.

Something along these lines:

    public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, DisplayMode mode)
    {
     // put a switch statement here to either
     // add html attribute for readonly
     // or
     // return null/emptystring
    }

With this extension your view could have @Html.TextBoxFor(x => x.Prop, Model.PropMode)

That would clean your razor views a bit.

Also keep in mind that readonly field values could be still altered (dev tools, firebug). That's something to take care of in your HttpPost action.

OTHER TIPS

To do so, you could use XACML (eXtensible Access Control Markup Language - an attribute-based access control implementation) and a Policy Decision Point. With that you can actually bind controls / widgets visibility / enabled state to a decision e.g.

approveButton.Enabled = PDPUtil.authorized(Page.User.Identity.Name, purchaseOrderObject);

Policies are defined outside your app and can be as fine-grained as you like e.g.

Managers can approve a purchase order if the poLocation == userLocation.

The policies can be then applied to different systems, not just .NET controls. The same policy could be applied to an HttpModule or a WCF message inspector.

I wrote an article on XACML and C# here: http://www.webfarmr.eu/2012/02/fine-grained-access-control-using-xacml-in-c-applications-and-the-net-framework/

Also check out http://www.axiomatics.com/policy-decision-points.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top