How: Inheriting PageView and Controllers in ASP.NET MVC

If I wanted to add general functionality to all pages, I create BasePage and get all ASPX pages out of it, how can you do this for page views and controllers in MVC?

+4
source share
3 answers

For views (“Pageviews,” as you call them), you probably won’t have too much data / behavior to group in the base class, but you can still. You would define a class that inherits from System.Web.UI.Page and places all the common logic there. Then, in your code, behind the files for the views (in ASP.NET MVC 1.0 there is no code behind the BY DEFAULT file for the view, but you can create one ), the class view from this general class is inherited.

For the controller, you can create a class that leads from System.Web.Mvc.Controller and puts all common things into it. Then derive all controller classes from this class. There are no restrictions on names, namespaces and file locations.

+2
source

Well for the controller, you simply inherit from System.Web.Mvc.Controller and add custom functions:

 public class MyController : System.Web.Mvc.Controller { public MyController() : base() { ViewData["someDataInMasterPage"] = "Hello World!"; } } 

If you have a master page that tries to retrieve some ViewData using the key above, this will make it available in all your views if their controller inherits MyController.

You can inherit from ViewPage to define custom functions. See For example, this SO question: Extending WebFormView in MVC

+2
source

if you want all views to share the same script, use the main page with all the script functions and put a place in it:

 <asp:ContentPlaceHolder ID="MainContent" runat="server" /> 

And then each subview then links to the main page.

 <%@ Page Title="" Language="C#" MasterPageFile="Site.Master" Inherits="OpenProjects.Web.Mvc.ApplicationView %> <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server"> </asp:Content> 

For controllers, create your own application controller that inherits from the built-in MVC controller, and then get your controllers from inheritance instead, not just the controller

+1
source

All Articles