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 e开发者_运维技巧xtraneous 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.
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.
精彩评论