I've written a custom authorization attribute derived from System.Web.Mvc.AuthorizeAttribute. I'm using it successfully from my controllers to restrict the access to certain features.
public class ArticleController : Controller
{
[CustomAuthorize(Role.Administrator)]
public ActionResult Delete(int id)
{
// ...
}
}
And that works fine. Now I want to show or hide HTML elements according to the same authorization logic. For example, in my view "Article", I want to hide the action button "Delete" if the user is not a administrator. I've written something like that:
<ul id="menu">
<li>@if (User.IsInRole(Role.Administrator)) {
@Html.ActionLink("Delete", "Delete", "Article", new { id = article.ID }, null)
} </li>
</ul>
It works fine as well, but it creates code logic duplication because I need to specify twice the necessary credientials to perform an action:
What is the best way to avoid this duplication? Is there any way to reuse my custom authorization attribute from views?
A custom helper should be the best option, something like:
@Html.SecureActionLink("Delete", "Delete", "Article")
This helper would check on some kind of service to see if the current user/role has permission on this link.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With