Ashwani K
Ashwani K

Reputation: 7990

Create a strongly typed view which inherites a class which is concrete

I am having one class called BaseClass which contains some logic applicable to whole web site.

In order to create a strongly typed view we need to inherit the page from System.Web.Mvc.ViewPage generic class. But In our case I have to Inherit the BaseClass from System.Web.Mvc.ViewPage to apply some common settings, but the BaseClass should be inherited from System.Web.Mvc.ViewPage<> generic version. But I cannot inherit the BaseClass from System.Web.Mvc.ViewPage<> as it will change other class also. So I created one more class of type BaseClass<> inheriting it from System.Web.Mvc.ViewPage<> and copied the whole code of BaseClass in BaseClass<>. But the code in BaseClass is controlled by other team so it will be changed frequently so my BaseClass<> should be in sync with BaseClass. Please help me in eliminating the code duplication or any other approach to make strongly typed View.

Thanks Ashwani

Upvotes: 1

Views: 287

Answers (3)

ten5peed
ten5peed

Reputation: 15890

Ok... it seems like you can't change the use of this BaseClass for your views.

How about duplicating the logic of ViewPage<TModel>? Have a look at the ViewPage`1.cs file that is in the asp.net mvc source code and duplicate that. That would be the easiest way...

E.g.

public class BaseClass : ViewPage
{
    //Custom logic for africa here
}

public class BaseClass<TModel> : BaseClass
{
    //Copy and paste all the code from ViewPage`1.cs
    //It's not much - about 50 lines.
}

HTHs,
Charles

Ps. The link to the source code is for asp.net mvc 2

Upvotes: 1

Gopher
Gopher

Reputation: 927

public abstract class MyBaseView<T> : ViewPage<T>
{
//common logic here
}

public class UserView: MyBaseView<MyUserInfo>
{}

Upvotes: 0

rrejc
rrejc

Reputation: 2682

Ouch...

I am not sure what you are having in your BaseClass. But I think the best option is to create a BaseViewModel (maybe your BaseClass is you BaseViewModel> and then create specific ViewModels (which inherits from BaseViewModel) for each page.

For example your ViewModels should look something like this:

public abstract class BaseViewModel
{
  public string SiteTitle {get;set;}
  public int SomeProperty{get;set;}
}

public class UserViewModel: BaseViewModel
{
  public string UserName{get;set;}
  public string Email{get;set;}
}

and you should create strongly typed view like this:

System.Web.Mvc.ViewPage<UserViewModel>

You can take a look at AutoMapper to simplyfy the mapping process from your custom classes to ViewModels.

Cheers

Upvotes: 1

Related Questions