Tech Junkie Blog - Real World Tutorials, Happy Coding!: Hour 18 ASP.NET Core: Add Area For Administrators

Monday, April 25, 2022

Hour 18 ASP.NET Core: Add Area For Administrators

An ASP.NET MVC can get big, and it could be overwhelming.  Areas are a way to break up the application into smaller segments,  A perfect candidate for an Area is the Administrative features of the site because it has multiple pages, and functionalities.  So it is a good idea to segment off the Administration area to its own area (no pun intended).



To add an Area to your MVC application right-click on the project and click "Add", then select "Area..."


















Type in the word "Admin" in the "Add Area" dialog












Make sure AreaRegistration,RegisterAllAreas method is called in the Global.asax.cs file so that your "Admin" area is registered















The Areas folder structure should look like this.















Now we want to create a controller for the Admin Area, right-click "Controllers" folder under "Admin" and click "Add", then select "Controller"








Select and empty controller










Call the controller "HomeController", then click "Add"










Open the HomeController.cs file under the "Contollers" folder in the "Admin" folder, right-click on the "Index" method, then click "Add View"

















Except the default options for the view and select "Add"






















Open the Index.cshtml and type in the following code

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<h1>This is from the Admin Area</h1>

Now if you type in the route /Admin/Home/Index you see the message "This is from the Admin Area"























Now comes the annoying part about Areas, when you type in the route /Home/Index you will get an error that the Home controller is not unique.  That is because the MVC framework puts all controllers in finds in the application into a flat list regardless of namespace.





























In order for us to fix this issue we need to specify the namespace in both the "AdminAreaRegistration.cs" file and RouteConfig.cs file

First let's fix the AdminAreaRegistration.cs file, open the file and type in the following code in the RegisterArea method


        public override void RegisterArea(AreaRegistrationContext context) 
        {

            context.MapRoute(
                "Admin_default",
                "Admin/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional },
                new string[] { typeof(NorthwindCafe.Areas.Admin.Controllers.HomeController).Namespace }
            );
        }


Notice in the last line new string[] { "NorthwindCafe.Areas.Admin.Controllers" } we set the namespace for the Admin Area controls so that MVC looks for the controllers that are only in that namespace









Now let's do the same thing for the RouteConfig.cs file. Open the RouteConfig.cs file and change the routes.MapRoute method to the following


            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
                namespaces: new string[] {typeof(NorthwindCafe.Controllers.HomeController).Namespace}
            );

Now when you type in the route /Admin/Home/Index you see the Admin Index.cshtml page













And when you type in the /Home/Index route you see the application home page



















34 comments:

  1. nice suggestions

    https://thecakeryshop.in/category/anniversary

    ReplyDelete
  2. useful information

    https://thecakeryshop.in/

    ReplyDelete
  3. Good and interesting. For any mobile-related information visit us at best seo service

    ReplyDelete
  4. Pg Slot เครดิตฟรี หรือ มีกิจกรรมที่แจกเครดิตฟรี PG SLOT มีโปรโมชั่นและก็ยังมีแอดมินทำงานที่จะรอเอาใจใส่ดูแลผู้เล่นตลอด 24ชั่วโมง ฝากไม่มีอย่างต่ำที่เว็บของเรา Pg-Slot.Game

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. I’m really impressed with your article.
    https://wiser.eco/fast-fashion-brands-to-avoid/

    ReplyDelete
  7. pg slot 168galaxy ยอดเยี่ยมที่เกมที่มีระบบระเบียบทำการระดับประเทศแบบอย่างเกมน่าเล่นเกมแนวหน้าที่สมัยบริการ24 ช.ค่ายเกม pg slot มาแรงและเป็นค่ายเกมที่มีผู้เล่นเข้าเล่นเยอะ

    ReplyDelete
  8. เล่น pgslot ให้ได้กำไร คือคำตอบที่คุณต้องการ ทำไมถึงเชื่อมั่นว่า PG SLOT พีจีน่าสนใจและเป็นที่นิยมของผู้เล่นสล็อต? เพราะว่า PG มีระบบการเล่นที่ง่าย และสะดวกสบายสำหรับผู้เล่นทุกระดับ

    ReplyDelete
  9. Thank you for sharing this informative and well-written blog post. Your insights are not only thought-provoking but also a great source of inspiration.java certification

    ReplyDelete
  10. Urban Plus Careers is a comprehensive guide for individuals seeking success and fulfillment in the dynamic landscape of modern urban professions. This insightful exploration delves into the unique challenges and opportunities presented by urban-centric careers, providing invaluable insights and strategies for navigating the intricate pathways of professional growth.

    ReplyDelete
  11. Indulge in the epitome of opulence at Elan Imperial, Sector 82's premier new mall in Gurgaon, where luxury shopping reaches new heights. This upscale destination seamlessly blends architectural grandeur with a curated selection of high-end brands, creating an unparalleled shopping experience for discerning individuals.

    ReplyDelete
  12. The Arbour by DLF stands as a testament to the pinnacle of luxury living, redefining opulence with its Ultra-Spacious Apartments and a harmonious blend of modern design and comfort. This exclusive residential enclave, crafted by the renowned DLF Group.

    ReplyDelete
  13. Shrishivmahapuran - Vedrishi stands as a monumental compilation, a spiritual treasure trove that delves into the profound teachings of Lord Shiva. This magnum opus captures the essence of the ancient wisdom imparted by the revered deity, weaving together a tapestry of spiritual guidance, mystical insights, and timeless philosophy.

    ReplyDelete
  14. Very nice, I really enjoyed reading this post. You can also try- real estate image editing services.

    ReplyDelete
  15. Golf Hills Residences by M3M is a luxurious residential project that redefines opulence and modern living in the heart of Sector 79, Gurgaon. Nestled amidst the lush greenery of a meticulously designed golf course, this development seamlessly blends tranquility with urban sophistication, offering residents a lifestyle that truly elevates their standards.

    ReplyDelete
  16. "The Epic Tapestry Unveiled: Harivamsa Purana - A Three-Volume Odyssey" is a masterful exploration into the depths of Hindu mythology and spirituality, meticulously crafted to bring to life the intricate tales woven within the Harivamsa Purana.

    ReplyDelete
  17. Eoan Technologies, based in Gurgaon, is a Leading Healthcare Marketing agency specializing in internet marketing solutions for the healthcare industry. With a commitment to leveraging digital strategies to enhance the visibility and reach of healthcare providers.

    ReplyDelete
  18. Step into a world of sophistication and style as we proudly introduce "Elevate Your Space," a dynamic collaboration of Houston's Premier Interior Design Dream Team. This visionary ensemble of talented designers is set to transform your living spaces into breathtaking works of art, seamlessly blending luxury and functionality.

    ReplyDelete
  19. Introducing DLF The Arbour, a prestigious residential project located in Sector 63, Gurugram. Designed by the renowned DLF Group, this development offers an exquisite collection of 4 BHK ultra-luxurious apartments.

    ReplyDelete
  20. Elevate the aesthetic appeal of your closet and bathroom spaces with the transformative power of Curtains By Design. Whether you're looking to add a touch of elegance, create privacy, or simply update the look of your interiors, curtains offer a versatile and stylish solution.

    ReplyDelete
  21. The Srimadbhagavata Mahapurana, often referred to simply as the Bhagavata Purana, stands as one of the most revered texts within Hinduism. This ancient scripture, composed in Sanskrit, encapsulates a profound narrative journey through divine tales and timeless wisdom, serving as a spiritual guide for seekers across generations.

    ReplyDelete
  22. We design attractive travel websites. For your travel website designrequirement visit us now ! or call us at : +91 9990361301

    ReplyDelete
  23. Tailored Elegance: Complete Design Services by Curtains By Design embodies the epitome of sophistication and refinement in interior design. With a commitment to excellence and an eye for detail, Curtains By Design offers a comprehensive range of services dedicated to transforming spaces into timeless masterpieces.

    ReplyDelete
  24. "Transforming Spaces" is an exploration of cutting-edge methods and creative strategies in Residential Interior Design. This captivating book delves into the realm of innovative approaches, offering readers a comprehensive insight into how designers conceptualize and execute transformative projects.

    ReplyDelete
  25. Vedrishi Swami Vidyanand Saraswati stands as a luminous figure, a beacon of profound wisdom in the vast ocean of Vedic knowledge. With a countenance that exudes serenity and a demeanor steeped in humility, he embodies the essence of a true seeker, dedicated to unraveling the depths of Vedic wisdom.

    ReplyDelete
  26. As someone new to this topic, I found your explanations incredibly helpful. Thank you for breaking it down in such a clear and concise manner. You can also visit our page Click here

    ReplyDelete
  27. "Wow, what an insightful perspective! This really got me thinking. Thanks for sharing!"
    visit ; SMARTWORKS

    ReplyDelete
  28. Your passion for this subject is contagious! It's evident that you genuinely care about what you're writing. You can also visit our page Microsoft Dynamics Business Central Partners in India

    ReplyDelete
  29. What an insightful perspective! Your analysis really sheds light on this topic. Visit your pagesmartwork

    ReplyDelete
  30. Redbluearts Academy opens up its beautiful gallery and space to host Birthday Parties & its a best birthday party place in sugarland. Bring your own cake, snacks, drinks and decorations. We will provide you all with best deal.

    ReplyDelete
  31. Excellent guide on adding areas to ASP.NET MVC! Makes managing complex apps much easier. Thanks for the clear instructions!......Ukraine Dedicated Server

    ReplyDelete
  32. Your blog provides invaluable insights into hosting services. It's a must-read for those seeking reliable information. Well done on the comprehensive overview!"India VPS Server'

    ReplyDelete
  33. We are pleased to present "Onlive Server," a dynamic partnership between Houston's Premier Interior Design Dream Team, and invite you to enter a world of refinement and flair. Your living areas will be transformed into breathtaking works of art by this imaginative group of gifted designers, who will skillfully combine luxury and functionality.........India VPS Server

    ReplyDelete

Search This Blog