Developer forum

Forum » Templates » Extending Razor ViewModels

Extending Razor ViewModels

Kim Pilgaard
Reply

I have been looking into extending your Page and Paragraph ViewModels for our frontenders by creating models which inherits from your classes. However as far as I can tell this is not possible since you have hardcoded the usage of PageViewModel and ParagraphViewModel when you render content. This gives a type mismatch when you attempt to assign this value to my custom type which is correctly identified by the template.

Do you intend to implement the possibility for us to create our own custom ViewModels and if yes when is it expected to be ready?


Replies

 
Nicolai Pedersen
Reply

You can create custom viewmodels already, see https://doc.dynamicweb.com/api/html/c0c19636-f848-e866-6208-ade44285310b.htm

But you cannot create your own version of the existing viewmodels in Dynamicweb. We could easily give you extensibility point for that. Will have that drafted up.

But you can try to change:

@inherits Dynamicweb.Rendering.ViewModelTemplate<Dynamicweb.Frontend.PageViewModel>

to

@inherits Dynamicweb.Rendering.ViewModelTemplate<MyCustom.PageViewModel>
var customViewmodel = new MyCustom.PageViewModel(Pageview);
@Pageview.Template.SetViewModel(customViewmodel)

With a bit of luck, that will do the trick.

BR Nicolai

 
Kim Pilgaard
Reply

I have justed tested it quickly and it does not look as a custom viewmodel which inherits from ViewModelBase can be used in page templates (assume paragraph is the same problem). If you write  @inherits Dynamicweb.Rendering.ViewModelTemplate<SomeCustomModel> then it will throw an exception at the point where Dynamicweb attempts to assign a model of type PageViewModel as the model for the template (which is of the type "SomeCustomModel")..

 
Nicolai Pedersen
Reply

Ah, yes - we have a test for that :-).

Have to discuss with the team how we can support extendable viewmodels

BR Nicolai

 
Kim Pilgaard
Reply

Sound great Nicolai, I'm eagerly looking forward to what you come up with :)

In case it is helpful my "shoot from the hip" thoughts would be something along the line of this:

1) Instead of hardcoding the use of PageViewModel/ParagraphViewModel utilize the type from the template.

2) Require that ViewModels on page templates extends PageViewModel and ParagrapViewModel for ViewModels in paragraph templates.

3) Make a virtual function which you call when you are done setting up the ViewModel.

That way you can continue to fill it with data as if it is a PageViewModel/ParagraphViewModel and we can overide the virtual function to ensure we fill our data after your data is avaliable.

 
Jesper Holm Damgaard
Reply

Any progress on this?

 
Søren Ravn Lund
Reply

Anything new on this?

 
Nicolai Pedersen
Reply

No news... indecision

 

You must be logged in to post in the forum