superartsy
superartsy

Reputation: 489

How to dynamically create partial views

I have a table in my database called Programs. I want to display a tab for each program .I am trying to create a partial view to do this and then I want to include the partial view to every view that will need to have those tabs. My partial view looks like below.

<div id="tabs">

    <ul>
        <li id="HomeTab">@Html.ActionLink("Dashboard", "Index", "Home")</li>
        <li id="Program1Tab">@Html.ActionLink("Program1", "Index", "Program")</li>
        <li id="Program2Tab">@Html.ActionLink("Program2", "Index", "Program")</li>
    </ul>
</div>

I am hoping to dynamically create the tabs using something like

  @foreach (var ptype in Model)
    {
       <li id=\"@ptype.Name\"Tab>@Html.ActionLink(ptype.Name, "Index", "Project")</li>
    }

however I am wondering how I can load the tabs without using a controller. Can I use a helper class/method to directly access the model bypassing the controller?

update: I also tried by creating a helper method

namespace MyProject.Helpers
{
    public class ProgramTypes
    {
        public static List<ProgramType> ProgramTypesList()
        {
            MyDbContext db = new myDbContext();
            return db.ProgramTypes.ToList<Programtype>();

        }
    }
}

and then accessing them using

 @foreach (var ptype in MyProject.Helpers.ProgramTypes.ProgramTypesList())

however i am not sure if this is the correct thing to do.

Upvotes: 0

Views: 1930

Answers (1)

Bohdan
Bohdan

Reputation: 2004

The best solution is - passing collection of programs to your view

@model IQueyrable<Program>
<div id="tabs">
    <ul>
    @foreach (var ptype in Model)
    {
       <li>@Html.RenderPartial("ProgramTab", ptype)</li>
    }
    </ul>
</div>

so you have to create another partial view where you will display program details. If you want organize this like tabs you should use something like jquery tabs

you don't have to use actionlink just RenderPartial or RenderAction

Upvotes: 1

Related Questions