Five New Optimizely Certifications are Here! Validate your expertise and advance your career with our latest certification exams. Click here to find out more

ViewModel to inherit more than one page type

Vote:
 

I have a question page with two properties

public virtual XhtmlString Description { get; set; }
public virtual Url ButtonLink {get; set; }


I have an answer page with one property

public virtual ContentArea ContentAreaContent {get; set;}


Now I want to have a view with both answer and question page properties.


But how do I create a ViewModel inheriting both the page properties


Here is my ViewModel 
 public class AnswerViewModel : PageViewModelBase   

{        public AnswerViewModel(Answers currentPage, ISettings siteSettings)            : base(currentPage, siteSettings)        {}
    }
Controller

[HttpGet]       

public ActionResult Index(Answers currentPage)       

{           

var model = new SAnswerViewModel(currentPage, SiteSettings);           

return View(model);       

}

View

    @Html.PropertyFor(x => x.CurrentPage.SelfServiceContentArea)

The above process is working fine if I just inherit Answers into ViewModel. But I would also want to include the properties of Questions page as well. 
What changes do I make to ViewModel, Controller and View to also include the Questions page?

#148705
May 20, 2016 16:46
Vote:
 

I would strongly recommend to rethink viewmodel structure in your project and avoid these cases - when you would need to inherit from more than 1 class - just because it's not supported at all in our .Net world.

Can you maybe give a try to so called composite view models, like:

public class MyNewViewModel
{
    public Answers AnswersPage { get; set; }
    public Questions QuesitonsPage { get; set; }
}

That would give opportunity to avoid necessaity for multiple inheritance.

#148708
May 20, 2016 17:14
Vote:
 
#148710
May 20, 2016 17:20
Vote:
 

You can add a reference to the question page in your answer view model:

public class AnswerViewModel : PageViewModelBase<Answers>   
{        
    public AnswerViewModel(Answers currentPage, ISettings siteSettings) : base(currentPage, siteSettings)
    {
    }
    public Questions QuesitonsPage { get; set; }
}

and populate the reference in the controller:
var model = new SAnswerViewModel(currentPage, SiteSettings);

model.QuestionsPage = <Code for getting the question page to this answer page>

#148767
May 23, 2016 15:50
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.