开发者

Creat a list of links from controller actions ASP.NET MVC

开发者 https://www.devze.com 2022-12-09 00:11 出处:网络
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>

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 ea开发者_StackOverflow中文版ch item?


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>


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

0

精彩评论

暂无评论...
验证码 换一张
取 消