Reputation: 26061
I'm trying to disable/enable controls based on user permission using a custom security framework . I'm trying to use this code in the codebehind file
protected void OnLoadComplete(object sender, EventArgs e)
{
if ((ViewData[Constants.Permission]).Equals(Security.UserAccess.ReadOnlyAccess))
{
foreach (var control in this.Page.Controls )
{
control.IsReadOnly = true;
}
}
}
But the IsReadOnly property of control is not available. Is there a way I can fix this or a better way to achieve this?
---Update---
Controller.cs
[Proxy.AimsAccessLevel]
public ActionResult Edit(int clientId)
{
ClientId = clientId;
//SetClientDetails();
var Selection = new SelectionArgs(clientId, null);
if (Selection.SelectionFlag == null || Selection.SelectionFlag == "N")
Selection.EffectiveDate = new DateTime(DateTime.Now.Year + 1, 1, 1);
return View(Selection);
}
proxy.cs
public class AccessLevel : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
Roles = Constants.AccessLevel.FullEdit + Constants.AccessLevel.ReadOnly.ToString() +
Constants.AccessLevel.RestrictedEdit;
return base.AuthorizeCore(httpContext);
}
}
Upvotes: 0
Views: 407
Reputation: 5024
You shouldn't be using codebehind with ASP.Net MVC - it goes against the principles of MVC. A view should not be the thing deciding if a user has permissions or not. Deciding if a page is viewable belongs at the controller level.
A better way to handle permissions is by using the [Authorize]
attribute on your controllers. Ie,
public MyController : Controller
{
[Authorize(Roles = "admin")] // Uses default FormsAuthentication
public ActionResult Index()
{
// ...
}
}
You can write your own Authorize
attribute to tie into your custom framework:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization( AuthorizationContext filterContext )
{
// ... authorization stuff here ...
}
}
Then use it on your controller action:
public HomeController : Controller
{
[MyAuthorize]
public ActionResult Index()
{
// ...
}
}
Upvotes: 4