Sina Sohi
Sina Sohi

Reputation: 2779

How to dynamically create several ActionLinks from the Controller in MVC?

I'm using MVC where I have a list of strings that I would like to point to a new page. I'm using Razor and am very new to MVC and cannot seem to find the answer to my question through google.

My list could contain of the following:

"hello"
"goodbye"
"seeya"

I know how to insert strings from the controller to the html page using ViewBag, and I would use the following actionlink if I had a fixed set of strings:

@Html.ActionLink("viewedName", "ChemicalClass", new { mystring = "hello" })
@Html.ActionLink("viewedName", "ChemicalClass", new { mystring = "goodbye" })
@Html.ActionLink("viewedName", "ChemicalClass", new { mystring = "seeya" })

As I understand it, this would generate 3 links that would redirect to the subpage "ChemicalClass", and it would contain the one of the 3 parameters, depending on the link that was clicked.

My quesiton is, how can I do the same, but have the ActionLinks created dynamically, since I won't know how many links are going to be created, nor the content of the strings. My goal is to show these links on the webpage in (preferabely) a list form, e.g.:

<ol>
    <li>
        hello
    </li>
    <li>
        goodbye
    </li>
    <li>
        seeya
    </li>
</ol>

Where each element in the list is a link and not just a string.

Upvotes: 2

Views: 4659

Answers (3)

PaulBinder
PaulBinder

Reputation: 2052

Create a view model that stores a collection of links

Model

public class ViewModel
{
    public IList<string> Links { get; set; }
}

populate that model in your controller

Controller

public ActionResult Index()
    {
        var model = new ViewModel
            {
                Links = new List<string>
                    {
                        "Hello",
                        "Goodbye",
                        "Seeya"
                    }
            };
        return View(model);
    }

and finally your view View

@model MvcApplication1.Models.ViewModel
        <ol>
        @foreach (var item in Model.Links)
        {
            <li>
            @Html.ActionLink("viewedName", "ChemicalClass", new { mystring = item })
            </li>
        }
        </ol>

Your class holds your collection of strings and razor loops over them to produce your links.

Upvotes: 5

L_7337
L_7337

Reputation: 2748

I have something like this in one of my Views:

@foreach (var item in Model.MyList)
    {
        <li>
            @Html.ActionLink("Select", "ActionName", "Chemical", new {id = item.AdmNum}, new { @class = "label label-info"})
        </li>
    }

Upvotes: 0

Deshmukh
Deshmukh

Reputation: 29

you can use something like this.

                <ul>
                 @foreach (var x in Model)
                 {
                     <li><a href="#">@x.myString </a></li>
                  }
                </ul>

Upvotes: 0

Related Questions