Share an action with two views

advertisements

I'm working on a website which needs a control panel that is used by multiple user types. I've been wondering is it possible to make different views that have different layouts but they are similar in operation use a single action so that I wouldn't need to re-write them again?

For example, both Admin and Supervisors can modify employee details but the admin views have a different layout than the supervisor. I can write different actions for each view, but the code in both actions would be exactly the same as they do the same operation. So can one action be shared with many views ?


You certainly can. However, the approach depends on how you determine which layout to present and where that information comes from. The most straight-forward approach is to determine the type of users (Role) and based on the user's role you can render a specific view within the same action method...

public ActionResult YOUR_ACTION()
{
    //do your processing
    Role role = GetCurrentUserRole();

    if(role.Name = "Admin")
        return View("ViewForAdmins");
    else if (role.Name = "Supervisor")
        return View("ViewForSupervisors");
    else
        return View("EveryoneElseView");
}