Search code examples
asp.net-mvc-3partial-viewsrenderpartial

Refresh partialview in _Layouts.cshtml


I have the following partial view:

<span>Login Status</span>
@{
    if (ViewBag.UserId > 0)
    {
        @Html.ActionLink("Log Out", "LogOut", "Home", null);
    }
    else {
        @Html.ActionLink("Log In", "Login", "Home", null);
    }
}

It's just a pretend login status area. Now, the idea is to have this appear in master page for my MVC site, so that it appears on all pages. Here's how I'm rendering it in the _Layout.cshtml file:

<div id="login">
   @{ Html.RenderPartial("LoginStatus"); }
</div>

What I'd like to have is, when the user clicks either the "Log In" or "Log Out" links, an action is performed (to log the user in/out) and then the partial view is refreshed - but the the rest of the page is left alone.

At the moment, when I click any of the links, the site navigates to "Home/Login" or "Home/Logout". I don't want it to render a view, I'd like to refresh just the partial view, regardless of which page I'm on.

What is the suggested way to do this?

Cheers. Jas.


Solution

  • You could use AJAX. So you could use jquery to unobtrusively AJAXify those links by subscribing for their click event and sending an AJAX request to the corresponding controller action which would return the partial view and update the DOM.