locked
ASP.NET MVC - how to set a Controller for the _Layout page? RRS feed

  • Question

  • User135423268 posted

    Good Day Everyone

    How can I create a Controller for the _Layout page (similar to Webforms Code behind), I have a methods of validation that I don't want to repeat on each page, so how can I make a Controller class for my _Layout?

    Thanks and Regards

    Saturday, June 22, 2019 4:32 AM

Answers

  • User-37275327 posted

    Inherit your controller from BaseController, and inherit BaseController from Controller class, put your global logic/validation on BaseController.

    Example :

    CustomerController.cs

    public class CustomerController : BaseController
    {
    
    }

    BaseController.cs

    public class BaseController : Controller
    {
     //Add your logic here
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, June 22, 2019 4:18 PM

All replies

  • User1120430333 posted

    You can try one of the options. You can use Bing or Google to seek out other options concerning the subject..

    http://www.dotnet-stuff.com/tutorials/aspnet-mvc/how-to-render-different-layout-in-asp-net-mvc

    Saturday, June 22, 2019 9:01 AM
  • User-37275327 posted

    Inherit your controller from BaseController, and inherit BaseController from Controller class, put your global logic/validation on BaseController.

    Example :

    CustomerController.cs

    public class CustomerController : BaseController
    {
    
    }

    BaseController.cs

    public class BaseController : Controller
    {
     //Add your logic here
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, June 22, 2019 4:18 PM
  • User135423268 posted

    Thanks for the response

    If I declare a viewbag on the BaseController can this be put on the Layout page via razor?

    Sunday, June 23, 2019 10:59 PM
  • User665608656 posted

    Hi amendoza,

    If I declare a viewbag on the BaseController can this be put on the Layout page via razor?

    Yes, we can do this.

    It just like you pass viewbag from a controller to a view.

    You could declare a public viewbag on the BaseController like : 

    ViewBag.BaseName = "I'm the public base";

    Then, in the Layout page, you can use this viewbag like this :

     @ViewBag.BaseName

    Then the viewbag value is displayed in the public section of your page.

    You could refer to this link for more details:

    https://forums.asp.net/t/1737254.aspx?How+to+pass+data+from+Controller+to+_Layout+cshtml

    Best Regards,

    YongQing.

    Monday, June 24, 2019 7:35 AM
  • User-37275327 posted

    If I declare a viewbag on the BaseController can this be put on the Layout page via razor?

    Yes, However you would better use the commonly used logic here, like checking a session, permissions, populating common functionality etc

    Tuesday, June 25, 2019 1:29 AM