如您所知,ASP.NET MVC支持視圖中模型字段的自定義視圖覆蓋。在Views
文件夾中有一個名爲Views\Shared\EditorTemplates
,Views\Shared\DisplayTemplates
等的文件夾,這些文件夾可以包含像Views\Shared\EditorTemplates\String.cshtml
這樣的文件,它將覆蓋在帶有String
字段的模型的視圖中調用@Html.EditorFor
時使用的默認視圖。自定義類型依賴模板加載器
我想要做的是使用這種功能的自定義模板。我想要有一個像Views\Shared\GroupTemplates
的文件夾,可能包含例如Views\Shared\GroupTemplates\String.cshtml
和Views\Shared\GroupTemplates\Object.cshtml
,我想創建一個HtmlHelper
方法,它允許我這樣稱呼,例如Html.GroupFor(foo => foo.Bar)
,這將加載模板String.cshtml
如果Bar
是String
屬性,在Object.cshtml
否則模板。
預期行爲的完整示例;如果Views\Shared\GroupTemplates\String.cshtml
包含此:
@model String
This is the string template
...和Views\Shared\GroupTemplates\Object.cshtml
包含此:
@model Object
This is the object template
我有這樣一個模型:
class Foo
{
public bool Bar { get; set; }
public String Baz { get; set; }
}
而像在Views\Foo\Create.cshtml
一個觀點:
@model Foo
@Html.GroupFor(m => m.Bar)
@Html.GroupFor(m => m.Baz)
當我渲染視圖Create.cshtml
,結果應該是這樣的:
This is the object template
This is the string template
應該如何GroupFor
實施?
我看了[ASP.NET MVC的源代碼](http://aspnetwebstack.codeplex.com),並簡單地從那裏複製了類型鏈生成算法。這基本上就是你說的,所以我會接受你的答案。 – dflemstr