如何初始化模型?

时间:2015-07-01 09:02:01

标签: asp.net-mvc

我有:

  public class MainMenuModel
    {
        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 SubMenuModel SubMenu { get; set; }

    }

我有:

 public class SubMenuModel
    {
        public string TransKey { get; set; }
        public string StateName { get; set; }
        public int NumberOfMenu { get; set; }

    }

如何在主菜单模型中初始化此子菜单模型?

我从这开始,但我不能获得子菜单模型的属性

   MainMenu.Add(new MainMenuModel() { TransKey = "PROMOTIONS", StateName = "", DisplayUrl = "", NumberOfMenu = "6.", hasSubMenu = true });

1 个答案:

答案 0 :(得分:2)

您可以在主菜单模型中初始化此子菜单模型,如下所示。在MainMenuModel的所有属性以及具有虚拟值的SubMenuModel下初始化。

        var mainMenuInstance = new MainMenuModel
        {
            DisplayUrl = "DisplayUrl",
            hasSubMenu = true,
            NumberOfMenu = "1",
            StateName = "StateName",
            TransKey = "TransKey",

            SubMenu = new SubMenuModel
            {
                NumberOfMenu = 4,
                StateName = "StateName",
                TransKey = "TransKey"
            },

            // If you have list of sub menus, initialize like this
            SubMenuList = new List<SubMenuModel>() { 
                new SubMenuModel { NumberOfMenu = 1, StateName = "StateName", TransKey = "TransKey" },
                new SubMenuModel { NumberOfMenu = 2, StateName = "StateName", TransKey = "TransKey" } }
        };