views:

131

answers:

2

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?

+3  A: 

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>
griegs
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'
Salt Packets
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.
griegs
+1  A: 

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: http://stackoverflow.com/questions/790464/accessing-the-list-of-controllers-actions-in-an-asp-net-mvc-application

AJ