user1365911
user1365911

Reputation:

Accessing a method in a BaseController from a Layout View in MVC4

In my MVC4 web application I have both a GlobalController which all controllers will inherit from so I have a single place that has all the common code that must run on each and every page. I also have a _MasterLayout.cshtml page that all my views use as there layout page. So far I have been able to put code in my GlobalController to fill ViewBag data with stuff to propagate dynamic data to the _MasterLayout.cshtml file.

I now need to figure out how to place buttons and/or links that people can click on to do things like register, login, logout, etc. As you could imagine these functions could be used on any page in my site so I would like the code for those to live in my GlobalController. I have already created public classes inside the GlobalController to do the actions I want but what I can not figure out is how to wire up a click on either a link or button placed on the _MasterLayout.cshtml file to the GlobalController public class?

I DO NOT WANT TO RENDER NEW VIEWS!

Upvotes: 0

Views: 1418

Answers (1)

Stephen Gilboy
Stephen Gilboy

Reputation: 5825

Your BaseController should only contain methods that controllers need to know how to do, like finding Views hence the View() method. Then every other controller should take care of their own jobs. So for Login, Logout, Register those all deal with account management. So you would create an account controller and put those actions inside

public class AccountController: BaseController {
    public ActionResult Logout() {
        /* logout user */
     }
    .....
 }

And then in your views you would just create an action link to to what you need.

<div id="header">
    @Html.ActionLink("Log me out", "Logout", "Account");
</div>

or you can call it directly

<div id="header">
    <a href="/Account/Logout">Log me out</a>
</div>

Hope this helps get you on the right track. I would also suggest going through the Music Store Tutorial for a better idea of working with MVC.

Upvotes: 1

Related Questions