tags:

views:

84

answers:

3

Hello All:

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

A: 

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

rrejc
Thanks Rrejc, in my application I have BasePage which Inherits from System.Web.Mvc.ViewPage in order to apply some UI setting (Like themes etc). But for the view to work have the same UI I need to inherit it from BasePage<> generic version which in tern should be inherited from ViewPage<>.
Ashwani K
A: 
public abstract class MyBaseView<T> : ViewPage<T>
{
//common logic here
}

public class UserView: MyBaseView<MyUserInfo>
{}
Gopher
+1  A: 

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

Charlino
Thanks Charlino, I will try that.
Ashwani K
Thanks Charlino, I worked.
Ashwani K