Passing extra data to EditorTemplate
Asked Answered
G

1

10

Lets say I have a LineItem (from the over used Shopping Cart example) and I want to render it using a EditorTemplate.

I am perfectly alright rendering it using a @Html.EditorFor(m => m.LineItems) from the parent view (partial or otherwise), but what is confusing is the best approach to pass some extra data (say a SelectList which has data coming in from the database) to the template.

Clearly I should not be polluting the LineItem model by adding these extraneous items (which are however required from a view's perspective.)

I am trying to see if there is a strongly typed way of doing this before resorting to ViewBag/ViewData tricks.

I have tried creating a 'LineItem' specific view model to pass the data in, but it mangles the names being generated by MVC and ads an extra layer to the collection (as I pass in a IEnumerable<> of the viewmodel to the EditorFor() call, instead of IEnumerable<> of the actual LineItem)

Also, is this a wrong use of the EditorTemplate? Is a LineItem requiring a dropdown which has options coming from a database table too much for a EditorTemplate?

Please guide me towards the MVC nirvana. While I wait for the answers, I will tryout other ideas!

To clarify: The reason I am considering using EditorTemplate is because of the automatic collection handling which it affords me. Otherwise the whole [id] business becomes too sticky.

Gottschalk answered 11/8, 2011 at 20:32 Comment(3)
Can't you use a ChildAction for this?Anam
Did you solve this issue since then?Rossini
Child action is not the best way to create input UIs. I solved this issue by using a variation of Steven Sanderson's method (blog.stevensanderson.com) to render a list of partial views.Gottschalk
R
12

I was facing the same problem recently and found this solution.

To summarize it, you should create your custom view model wrapping the original collection and the required supporting data. Then in the view calling the custom template you can use HtmlHelper extension method overloads to pass the supporting data to the ViewData dictionary. From your custom template you can then retrieve and use them frin ViewData.

I think this is a good workaround and basically this is what view models are intended for, at least it is much more better than extending or deriving from the original class just to provide extra data for the view.

Please let me know if it fits your scenario or if you find any other solution.

Rossini answered 12/8, 2011 at 15:14 Comment(2)
Although I ended up implementing it without EditorTemplates, this is what I would have used with Editor Templates.Gottschalk
The URL changed ... they must have switched CMSs: weblogs.asp.net/jongalloway//…Pigeontoed

© 2022 - 2024 — McMap. All rights reserved.