In this post, we will see how to render given below bootstrap Tab script in Asp.net MVC 5 view.
Here the number of tabs displayed in view would depend on count of members in the list.
1. Create ASP.NET MVC 5 project.
2. Define Member class as follows in “Member.cs” file
- public class Member
- {
- public int Id { get; set; }
- public string Name { get; set; }
- }
3. Add view to create action method and pass a list of members from controller Action method to razor view file. i.e. “create.cshtml”
- public ActionResult Create()
- {
- List<Member> members = new List<Member>();
- members = GetMemberList();
- return View(members);
- }
- private List<Member> GetMemberList()
- {
- List<Member> members = new List<Member>();
- members.Add(new Member{ Name = "member1" });
- members.Add(new Member { Name = "member2" });
- members.Add(new Member { Name = "member3" });
- members.Add(new Member { Name = "member4" });
- members.Add(new Member { Name = "member5" });
- return members;
- }
4. Using CSS classes, we can create a tabscript in our “create.cshtml” as shown below:
- @model IEnumerable<Member>
- <div class="container">
- @if (Model.ToList().Count > 0)
- {
- <ul class="nav nav-tabs" role="tablist">
- @{int i = 0;
- foreach (var item in Model)
- {
- if (i == 0)
- {
- <li class="nav-item">
- <a class="nav-link active" data-toggle="tab" href="#@item.Name">@item.Name</a>
- </li>
- }
- else
- {
- <li class="nav-item">
- <a class="nav-link" data-toggle="tab" href="#@item.Name">@item.Name</a>
- </li>
- }
- i++;
- }
- }
- </ul>
- <div class="tab-content">
- @foreach (var item in Model)
- {
- <div id="@item.Name" class="container tab-pane active">
- <br>
- <h3>@item.Name 's Tab Area </h3>
- </div>
- }
- </div>
- }
- </div>
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>