How can I build a tabbed menu in ASP.NET MVC?

后端 未结 4 454
-上瘾入骨i
-上瘾入骨i 2021-01-30 15:42

I would like to build a tabbed menu pretty similar to the profile management of StackOverflow.

tabbed menu StackOverflow http://img410.imageshack.us/img410/3037/image1nw

4条回答
  •  难免孤独
    2021-01-30 16:02

    Create View Model:

    public class UserViewModel {
        public myApplication.Models.User User;
    
        public string PartialViewName;
    
        public PartialViewModelBase Tab;
    }
    

    Create View Models for each Tab, derived from PartialViewModelBase:

    public abstract class PartialViewModelBase {
    }
    
    public class Tab1PartialViewModel : PartialViewModelBase {
        ...
    }
    
    public class TabNPartialViewModel : PartialViewModelBase {
        ...
    }
    

    Then make your View and PartialViews strongly typed:

    View:

    <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
    

    PartialViews:

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
    
    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
    

    Then in your View you can use your Partial Views as:

    <% Html.RenderPartial(Model.PartialViewName, Model.Tab); %>
    

    In your controller action:

    public ActionResult YourAction(string tab)
    {
        // check if tab is valid !!!
    
        var model = new UserViewModel {
            User = new myApplication.Models.User();
            PartialViewName = tab;
            Tab = TabRepository.GetTabByName(tab);
            /*
             * or
             * Tabs = (new Dictionary {
             *     {"Tab1", typeof(Tab1PartialViewName)},
             *     {"TabN", typeof(TabNPartialViewName)}
             *     })[tab];
             */
        };
    
        Return View(model);
    }
    

    Hope this helps.

提交回复
热议问题