On my main page, you want to display HTML only if the user is an administrator

My custom object has a property: IsAdministrator

Now I want to add HTML to every page, so on my main page, only if the user is an administrator.

What is the best way to do this?

I was thinking of creating a custom control and then calling RenderPartial.

But I need to access the Request object to find out if the user has authenticated, and if there are, to grab the user object from the cache, and then check the IsAdminstrator property.

reference

+3
source share
4 answers
  • basecustomviewmodel IsAdministrator.
  • OnActionExecuted , . , IsAdministrator .
  • actionresult customviewmodel, basecustomviewmodel 1)
  • , , basecustomviewmodel
0

, , , , , , .

MVC RenderAction, , .

0

:

public class HomeController : BaseController
{
  public ActionResult Index()
  {
    return View();
  }
}

BaseController:

public class BaseController : Controller
{
  public override void OnActionExecuted(ActionExecutedContext context)
  {
    base.OnActionExecuted(context);

    bool isAdministrator = context.HttpContext.Request.IsAuthenticated && context.HttpContext.User.IsInRole("Administrator");
    context.Controller.ViewData.Add("IsAdministrator", isAdministrator);
  }
}

:

<%
  bool isAdministrator = bool.Parse(ViewData["IsAdministrator"].ToString());
  if(isAdministrator) {
    Html.RenderPartial("Users/UserControl");
} %>

~/Views/Shared//UserControl.ascx

<%= Page.User %>.

0

, .

:

<asp:Placeholder ID="myPlaceholder" runat="server" Visible="">
   .... HTML for Admins
</asp:Placeholder>

- -

    if(user.IsAdministrator)
       myPlacholder.Visible = true;
   else
       myPlaceholder.Visible = false;
-1

Source: https://habr.com/ru/post/1730404/


All Articles