Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the base class of a razor view in the view code

Note that this is not a duplicated question. I know we can specify a base view type in the razor section of views/web.config. But I want my view1,view2 inherit from baseviewA, and the view3,view4 inherit from baseviewB. In razor how can I do this like that in ASPX engine:

<%@ Page Language="C#" Inherits="Test.Myproject.Web.Mvc.ViewBase" %>
<%@ Control Language="C#" Inherits="Test.Myproject.Web.Mvc.PartialViewBase" %>

EDIT I don't care about models. In my question baseviewA and baseviewB are totally different classes.

like image 629
Cheng Chen Avatar asked May 08 '12 03:05

Cheng Chen


2 Answers

You can change the base class in Razor with the @inherits keyword, your base classes just need to derive from System.Web.Mvc.WebViewPage.

So your sample:

<%@ Page Language="C#" Inherits="Test.Myproject.Web.Mvc.ViewBase" %>

Will be

@inherits Test.Myproject.Web.Mvc.ViewBase

Where

public class Test.Myproject.Web.Mvc.ViewBase : System.Web.Mvc.WebViewPage
{
}
like image 54
nemesv Avatar answered Nov 14 '22 23:11

nemesv


Inherits specifies the model type going to be used in the view. Same this can be done in Razor.

<%@ Page Language="C#" Inherits="Test.Myproject.Web.Mvc.ViewBase<Test.Models.MyModel>" %

is equivalent to following in Razor

@model Test.Models.MyModel

this is same in both views and partial views,So

<%@ Control Language="C#" Inherits="Test.Myproject.Web.Mvc.PartialViewBase<Test.Models.MyModelB>" %>

is equivalent to

@model Test.Models.MyModelB
like image 40
Manas Avatar answered Nov 14 '22 22:11

Manas