domingo, 22 de junho de 2014

MVC: Tabs in 5 steps

Hello,

A couple of weeks ago I was searching about how to build Tabs in MVC. But I couldn't find a great tutorial, so I decide to build one myself.

Step 1: Model
public class TabModel 
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool Visible { get; set; }        
    }

Step 2: Controller - Showing tabs
public enum TabType { TabName1, TabName2 };

private static List<TabModel> LoadTabs()
        {
            List<TabModel> tabList = new List<TabModel>(){
                new TabModel { Id=(int) TabType.TabName1, Name = "Tab 1", Visible = true },
                new TabModel { Id=(int) TabType.TabName2, Name ="Tab 2", Visible = true},
            };
            return tabList;
        }

public ActionResult Index()
        {
            List<TabModel> tabList = LoadTabs();

            return View(tabList);

        }

Step 3: View
@model List<LM.Site.Models.Tab>
<div id="tabs">
    <ul>
        @{
            foreach (var p in Model)
            {
                if (p.Visible)
                {
                    <li>
                        @Ajax.ActionLink(p.Name, "GetTab", new { id = p.Id }, new AjaxOptions
                  {
                      HttpMethod = "GET",
                      UpdateTargetId = "tab-content",
                      InsertionMode = InsertionMode.Replace
                  })
                    </li>
                }
            }
        }
    </ul>
</div>

<!-- 
Other guys were using 1 div for each tab, only one tab is enough.
-->
<div id="tab-content">

</div>

Step 4: Controller - Showing tab content
public ActionResult GetTab(int id)
        {
            switch ((TabType)id)
            {
                case TabType.TabName1:
                    return PartialView("Tab1");
                case TabType.TabName2:
                    return PartialView("Tab2");
                default:
                    return null;
            }

        }

Step 5: jquery.unobtrusive referenced, should be added at the view or template
@section scripts{
    @Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
}

Cheers, Adilson

Sem comentários:

Enviar um comentário