如何初始化MainMenuModel和SubMenuModel?

时间:2015-07-02 11:28:55

标签: asp.net-mvc

我有这个菜单模型:

          public MainMenuModel(string transKey, string stateName, string displayUrl, string numberOfMenu, bool hasSubMenu, List<SubMenuModel> subMenu)
                {
                    TransKey = transKey;
                    StateName = stateName;
                    DisplayUrl = displayUrl;
                    NumberOfMenu = numberOfMenu;
                    HasSubMenu = hasSubMenu;
                    SubMenu = subMenu;
                }
                public string TransKey { get; set; }
                public string StateName { get; set; }
                public string DisplayUrl { get; set; }

                public string NumberOfMenu { get; set; }
                public bool HasSubMenu { get; set; }

                public List<SubMenuModel> SubMenu { get; 

    set; 
}

我有submemnu模型:

    public SubMenuModel(string transKey, string stateName, string displayUrl, string numberOfMenu)
    {
        TransKey = transKey;
        StateName = stateName;
        DisplayUrl = displayUrl;
        NumberOfMenu = numberOfMenu;

    }
    public string TransKey { get; set; }
    public string StateName { get; set; }
    public string DisplayUrl { get; set; }
    public string NumberOfMenu { get; set; }

}

我的问题是如何初始化菜单和子菜单?我试过这个:

MainMenu.Add(new MainMenuModel("Promotions","default","default","6",true,new SubMenuModel("Promotions","default","default","3"));

但这不起作用。有人可以告诉我,如果我有这种模型结构或修改某种方式更容易,我如何初始化这个模型?

2 个答案:

答案 0 :(得分:1)

您的MainMenuModel有一个List,因此您必须在那里初始化列表。

var subMenuList = new List<SubMenuModel>()
    {
        new SubMenuModel("Promotions","default","default","3")
    }; 

var mainMenuModel = new MainMenuModel("Promotions","default","default","6",true,subMenuList);

MainMenu.Add(mainMenuModel);

答案 1 :(得分:1)

您传递SubMenuModel而不是List,因此您可以尝试执行以下操作:

MainMenu.Add(new MainMenuModel("Promotions","default","default","6",true,
new List<SubMenuModel>(){
    new SubMenuModel("Promotions","default","default","3")
});