EditorFor isn't working on derived type

只谈情不闲聊 提交于 2019-12-04 06:44:20

It appears that, while MVC won't locate the named template in this circumstance, it will find it if you specify the full path to the template. So, rather than fight this any further, I implemented the following helper function:

<Extension()> _
Public Function EditorForObject(Of T, TValue)(ByVal htmlHelper As HtmlHelper(Of T), ByVal obj As TValue) As IHtmlString
    Dim sTemplateName = "~/Views/Shared/EditorTemplates/" & obj.GetType.Name & ".vbhtml"

    'Return htmlHelper.EditorFor(Function(x) obj) <-- this should work but doesn't
    Return htmlHelper.Partial(sTemplateName, obj)
End Function

In English, this means: ask the object for its type name, form the explicit path to the editor template for that type, and then invoke HtmlHelper.Partial, specifying the object and the full path to the template. I'm sure this could be more general (and not hardcoded for vb), but it works.

Then the usage is like this:

@Html.EditorForObject(Model)

and actually, this is even better than what I was trying to do, which is much messier:

@Html.EditorFor(Function(x) Model, Model.GetType.Name)

Even without the template lookup problem, this would be handy, because it's convenient to be able to pass an object for editing (or display), rather than a dummy lambda that just returns that object.

Still, I think the lookup problem must be a bug in MVC. (If I ever get time, I guess I can check the source code.) Can anyone confirm or comment on this?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!