Wouter
Wouter

Reputation: 61

How to get to the parent object in an editortemplate?

In a custom editor template I want to access the parent object.

I'm using this code but this is probably not the best way to do it, especially when using nested views:

object parent = ViewContext.Controller.ViewData.Model;

Does anybody have a better idea?

Upvotes: 6

Views: 1606

Answers (1)

exploringintent
exploringintent

Reputation: 31

You shouldn't try climbing up the model hierarchy, if an editor requires extra data add that to the model or use ViewData. The call to render editor would look something like

<%: Html.EditorFor(model => model.EditorModel, new {viewDataKeyName = Model.AdditionalData})%>

Be careful when adding data that is vital to the editor this way, as it has to be included in each call to this template, that's why I prefer to include the values in the model itself.

Upvotes: 2

Related Questions