1

Is there a way to make a list of links for each action in controller instead of having to add

<li><%= Html.ActionLink("Link Name", "Index", "Home")%></li>

for each item?

2 Answers 2

3

yes there is.

You can either return a SelectList of key value pairs that you can render as anchor tags.

Or you can create a model in the, and this is not the best place for it, controller and return it to the view which you can then itterate through.

public class myAnchorList
{
  public string text {get;set;}
  public string controller {get;set;}
  public string action {get;set;}
}

then in your code create a List<myAnchorList>.

List<myAnchorList> Anchors = new List<myAnchorList>();

Fill the list with data and return.

return View(Anchors).

if you are already passing over a model then you need to add this list into the model you are returning.

Make sense? if not post a comment and i'll try to explain further.

Edit

Let me complete the picture now that i have a little more time.

On the client side you'd have this untested code;

<ul>
  <% foreach(myAnchorList item in Model.Anchors){ %>
    <li><%= Html.ActionLink(item.text, item.action, item.controller)%></li>
  <% } %>
</ul>
Sign up to request clarification or add additional context in comments.

2 Comments

does the List<myAnchorList> Anchors = new List<myAnchorList>(); and return View(Anchors) go inside of the same action ? public ActionResult Index() { } I get an error CS1061: 'object' does not contain a definition for 'Anchors' and no extension method 'Anchors'
myAnchorList is a class and the Anchors is the name of the generic list of type myAnchorList. So you need to place myAnchorList in a namespace your code has access to. then you pass the list to the view and the view will need access to the namespace as well.
2

In addition to griegs answer, it might be helpful to construct the list of controller actions via reflection. In which case you might want to look at:

new ReflectedControllerDescriptor(typeof(TController)).GetCanonicalActions()

Credit for this answer goes to: Accessing the list of Controllers/Actions in an ASP.NET MVC application

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.