jbutler483 jbutler483 - 1 year ago 37
HTML Question

Make a _Layout link differ in its action when it is used on a different page?

Say I have the layout page of (which is common in all pages):

| N | |
| A | |
| B | HERE |
| A | |
| R | |
| | |
| | |

And within my header I have something like:


| LINK_1 | Create | Edit | Remove
| |
| |

Whenever I go onto the 'locations' page, I want it to run the function 'AddLocation' function, but when it's on the 'Users' page, I want it to run the function 'AddUser' function.

Is this possible? (pressing the button on the _Layout page and it do something different depending on which content is being displayed at the time)?

If so, how should I be implementing this? On the _layout header? The specific function on each of the Locations/Users page itself?


If this isn't possible, how about creating a switch statement depending on the address value?


localHost/Locations //pressing it here will addLocation
localHost/Users //pressing it here instead will addUser

Answer Source

There are several ways to do this.

1 Custom section (preferred)

Using a custom section makes the most sense for you as it is optional and requires little setup:

In the layout where you want the button:

@RenderSection("addoption", required: false)

Then anywhere in your users view pages:

@section addoption{
   @Html.ActionLink("Add User", "adduser", "Users")

and in your location view pages

@section addoption{
   @Html.ActionLink("Add Location", "addlocation", "Location")

2 ViewBag

Another option is to pass the desired link values to the layout, from a specific controller action, using the ViewBag. This requires setup in multiple places.

e.g. in the layout page:

@Html.ActionLink(@ViewBag.AddTitle, @ViewBag.AddAction, @ViewBag.AddController)

and in the locations index action something like:

  ViewBag.AddTitle = "Add location";
  ViewBag.AddAction = "AddLocation";
  ViewBag.AddController = "Locations";

and in the Users index action something like:

  ViewBag.AddTitle = "Add user";
  ViewBag.AddAction = "AddUser";
  ViewBag.AddController = "Users";

3 Action Only

Another simple option is for your link to simply reference an add action with no controller.

@Html.ActionLink("Add", "add")

this will call the add action on the current controller. You can combine this with part of option 2 to set just the link text using a ViewBag value.