Zacho
Zacho

Reputation: 861

How Can I Hide Specific Elements on a Razor View Based on Security without Logic in View?

I have looked all over for elegant solutions to this not so age-old question. How can I lock down form elements within an ASP.Net MVC View, without adding if...then logic all over the place?
Ideally the BaseController, either from OnAuthorization, or OnResultExecultion, would check the rendering form elements and hide/not render them based on role and scope.
Another approach I have considered is writing some sort of custom attributes, so as to stay consistent with how how we lock down ActionResults with [Authorize]. Is this even possible without passing a list of hidden objects to the view and putting if's all over?

Other background info: We will have a database that will tell us at execution time (based on user role/scope) what elements will be hidden. We are using MVC3 with Razor Viewengine. We're utilizing a BaseController where any of the Controller methods can be overridden.

Any help on this would be deeply appreciated!

Upvotes: 7

Views: 3975

Answers (1)

Josiah Ruddell
Josiah Ruddell

Reputation: 29831

You could use a number of different methods:

  1. Send the user to a different view (display only view) based on the action filter, or a condition in the controller.
  2. On a field basis, you could build the logic into the editor templates to read custom data-annotations based on role/permission.
  3. You can build HTML helpers to handle the logic and render the appropriate partial view, css class, or text.

For more reading:

Upvotes: 2

Related Questions