开发者

In my master page, want to output HTML only if the user is an administrator

My user object has the property: IsAdministrator

Now I want to inject HTML on every page, so in my master page, only if the user is an administrator.

What is the best way to do this?

I was thinking of creating a user control, and then calling Re开发者_JS百科nderPartial.

But I need to access the Request object to see if the user is authenticated, and if they are, to grab the user object from the cache and then check the IsAdminstrator property.

Help?


  1. You create a basecustomviewmodel with a property called IsAdministrator.
  2. You overload the function OnActionExecuted in a base controller from which the other controller will inherits. Overload that will set IsAdministrator in function of the request.
  3. For each actionresult you pass a customviewmodel inheriting the basecustomviewmodel of 1)
  4. You create a partialview that will be passed in the master that take a basecustomviewmodel as model
  5. enjoy


i know this is answered and dont want to tread, but i have this kind of situation where if logged in i dont want to show the login on my masterpage.

i have downloaded the futures MVC and implimented RenderAction, this allows me have an action that checks for login, and renders the login view or the custom user view.

simple too


Controller:

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);
  }
}

Master page:

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

~/Views/Shared/Users/UserControl.ascx

Access the current administrator here with <%= Page.User %>.


Try adding a control on the front end and putting the content you would like to display inside it.

eg:

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

Then on page load in the code behind do something like this -

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜