问题描述:

I have implemented default identity2.0 for my mvc5 project. How can i disable an Action Link which renders a partialview(Ex: Create partialview) restricting the access of that partial view for an unauthorized user.

I can put the authorization attribute on the save action method. But i want to restrict the access of the partial view by disabling the Action Link which renders that partial view. To further demonstrate my question i have put the code below.

This is the save action method

 CustomAuthorize(Roles = "Admin")]

public ActionResult Save(ProductType producttype)

{

if (ModelState.IsValid)

{

//

objContext.SaveChanges();

return RedirectToAction("vwProductTypeIndex");

}

}

_Create Partial view with Save button

 @Html.BeginForm("Save", "ProductType"))

{

//

<input type="submit" id="btn" value="Save" class="btn btn-success" clientidmode="Static">

}

I want to disable the below Action Link (Add New Record) which is a button decorated with css which renders the above partial view.

@Html.ActionLink("Add New Record", "vwProductTypeIndex", "ProductType", new { A = "New" }, new { Class = "btn btn-primary page-scroll", style = "top:50px; margin-left:168px;width:120px;text-indent:-5px; position:relative;" })

How can i achieve this. All help appreciated. Thanks in advance!

网友答案:

You can check the role with the UserManager.IsInRole(userId,"Role") where UserManager is HttpContext.Current.GetOwinContext().GetUserManager(). You may want to create a helper method to make this easier to access.

Now you can use this directly in Razor or you could use it in the Get side of your controller to build a viewmodel or ViewBag setting.

So your code would end up looking something like:

@if (User.IsInRole("Admin"))
{
    @Html.ActionLink...
}
相关阅读:
Top