Question

On my website I have a header defined in my _Layout.cshtml. In that file, I'm doing this:

<li class="dropdown">
    @if (Request.IsAuthenticated)
    {
        <a href="#" class="dropdown-toggle menuItem" data-toggle="dropdown" style="color: red;">@User.Identity.Name <b class="caret"></b></a>
    }
    else
    {
        <a href="#" class="dropdown-toggle menuItem" data-toggle="dropdown">Profile <b class="caret"></b></a>
    }

    <ul class="dropdown-menu">
        @if (!Request.IsAuthenticated)
        { 
            <li><a href="/Account/Register">Register</a></li>
            <li><a href="/Account/Login">Login</a></li>
            <li><a href="/Account/ForgotPassword">Forgot Password</a></li>
        }
        else
        { 
            <li><a href="/Account/ChangePassword">Change Password</a></li>
            <li><a href="/Account/EditProfile">Edit Profile</a></li>
            <li><a href="/Account/Logout">Logout</a></li>
        }
    </ul>
</li>

So, I'm wanting to dynamically display my menu item name, as well as the contents based on whether the user is logged in or not.

99% of the methods in all of my controllers implement the [OutputCache] attribute. Because of this, after I login to the site, the menu item still says "Profile" with the corresponding menu items that go along with Profile (aka Register, Forgot Password, etc).

Do I have to turn off caching in my site in order for the username to show up immediately after logging in? This works perfect in my Development environment because I use #IF DEBUG statements around my caching attributes...

For example, here's my HomeController:

#if !DEBUG
    [OutputCache(Duration = 86400)]
#endif
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
Was it helpful?

Solution

I have used the donut caching library (mentioned by spender in the comments above) to solve a very similar problem.

Once your project has a reference to the MvcDonutCaching library, you can call an extended Html.Action method to exclude it from the cache e.g.

// Action(this HtmlHelper htmlHelper, string actionName, string controllerName, bool excludeFromParentCache)
@Html.Action("LoginStatus", "Home", true) 

To do this, you obviously would need to isolate the part you don't want to cache to its own action and partial view.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top