andrewb
andrewb

Reputation: 3095

Global action method in MVC _layout.cshtml file

I am porting over a WebForms ASP.NET project to MVC and I am not sure of the MVC way to go about something.

In the WebForms project there is a Masterpage with a logout button, it appears at the top right of every page.

<div class="userTableElementLogout">
    <asp:Button ID="LogOffButton" runat="server" OnClick="LogOffButton_Clicked" Text="LOG OFF" CausesValidation="false" />
</div>

And in the Masterpage codebehind file:

protected void LogOffButton_Clicked(object sender, EventArgs e)
{
    // Logout logic
}

So in my MVC project, _layout.cshtml file, I have this:

<div class="userTableElementLogout">
    <input type="submit" name="ctl01$LogOffButton" value="LOG OFF" id="log-off-button">
</div>

And I have several controllers with views which use the _layout.cshtml file.

How do I write one method/action which handles the click of that button?

Upvotes: 1

Views: 998

Answers (2)

Rajdeep
Rajdeep

Reputation: 802

  1. You should have your logout button in header.

  2. Use jQuery or Html.ActionLink to make a link between your button and the controller/action method, here it should be Account/logoff

  3. Have a partial view in layout with name _LoginPartial, which will have a button or image like

    <ul class="nav navbar-nav navbar-right">
        <li id="logOff" class="image-style">
            <img class="lhs" style="max-height: 30px; max-width: 30px;" src="@Url.Content("~/Images/logOut.png")" alt="Logout" title="Logout" />
        </li>
    </ul>  
    
  4. Now you can make it call your logoff method in Account controller using ajax call.

  5. create this method in Account controller

    public ActionResult LogOff() {
        this.AuthenticationManager.SignOut();
        // your logout logic here
        return this.RedirectToAction("Index", "Account");
    }
    

Better way is using jQuery, it lets you have much customisation.

I am assuming that your Account controller is the place where you put logic of login/logout and Index method is for the login page.

Upvotes: 1

Shyju
Shyju

Reputation: 218852

You can keep this submit button inside a form tag which will be submitted to one of your action method in which you can execute your code to do the log off logic.

@using(Html.BeginForm("Logoff","Account"))
{
   <div class="userTableElementLogout">
      <input type="submit"  value="LOG OFF" id="log-off-button">
   </div>
}

Assuming you have an HttpPost Logoff action method in Account controller which has the above mentioned logout logic.

If you want, you can also simply keep an anchor tag which does a GET request to one of your HttpGet action method (Logoff) as well.

Upvotes: 0

Related Questions