In power systems, the traditional, non-interactive, and manually controlled power grid has been transformed to a cyber-dominated smart grid. This cyber-physical integration has provided the smart grid with communication, monitoring, computation, and controlling capabilities to improve its reliability, energy efficiency, and flexibility. A microgrid is a localized and semi-autonomous group of smart energy systems that utilizes the above-mentioned capabilities to drive modern technologies such as electric vehicle charging, home energy management, and smart appliances. Design, upgrading, test, and verification of these microgrids can get too complicated to handle manually. The complexity is due to the wide range of solutions and components that are intended to address the microgrid problems. This article presents a novel Model-Based Design (MBD) methodology to model, co-simulate, design, and optimize microgrid and its multi-level controllers. This methodology helps in the design, optimization, and validation of a microgrid for a specific application. The application rules, requirements, and design-time constraints are met in the designed/optimized microgrid while the implementation cost is minimized. Based on our novel methodology, a design automation, co-simulation, and analysis tool, called GridMAT, is implemented. Our experiments have illustrated that implementing a hierarchical controller reduces the average power consumption by 8% and shifts the peak load for cost saving. Moreover, optimizing the microgrid design using our MBD methodology considering smart controllers has decreased the total implementation cost. Compared to the conventional methodology, the cost decreases by 14% and compared to the MBD methodology where smart controllers are not considered, it decreases by 5%.