@foreach (var property in ViewData.ModelMetadata.Properties.Where(x => x.ShowForEdit))
{
if (!string.IsNullOrEmpty(property.TemplateHint))
{
@Html.Editor(property.PropertyName, property.TemplateHint)
}
else
{
@Html.Editor(property.PropertyName)
}
}
但請注意,如果你不依賴建立的約定解決模板複雜的集合類型(又名~/Views/Shared/EditorTemplates/NameOfTheTypeOfCollectionElements.cshtml
),讓您的收藏屬性使用UIHint
:
[UIHint("FooBar")]
public IEnumerable<FooViewModel> Foos { get; set; }
然後~/Views/Shared/EditorTemplates/FooBar.cshtml
編輯器模板必須強制輸入爲IEnumerable<FooViewModel>
而不是FooViewModel
。所以要小心,如果這是你的情況,如果你想要獲取集合中的單個項目,則需要在此自定義模板中循環。它將不再是ASP.NET MVC,它將自動循環併爲每個元素調用編輯器模板。
UPDATE:
仍不能瑞普您的問題。
自定義屬性:
public class ACustomAttribute : Attribute, IMetadataAware
{
private readonly string _templateHint;
public ACustomAttribute(string templateHint)
{
_templateHint = templateHint;
}
public void OnMetadataCreated(ModelMetadata metadata)
{
metadata.AdditionalValues["foo"] = "bar";
metadata.TemplateHint = _templateHint;
}
}
型號:
public class MyViewModel
{
[ACustom("Something")]
public IEnumerable<int> Foos { get; set; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Foos = Enumerable.Range(1, 5)
};
return View(model);
}
}
視圖(~/Views/Home/Index.cshtml
):
@model MyViewModel
@using (Html.BeginForm())
{
@Html.EditorForModel()
}
對象類型
編輯模板(~/Views/Shared/EditorTemplates/Object.cshtml
):
@foreach (var property in ViewData.ModelMetadata.Properties.Where(x => x.ShowForEdit))
{
if (!string.IsNullOrEmpty(property.TemplateHint))
{
@Html.Editor(property.PropertyName, property.TemplateHint)
}
else
{
@Html.Editor(property.PropertyName)
}
}
自定義編輯模板(~/Views/Shared/EditorTemplates/Something.cshtml
):
@model IEnumerable<int>
<h3>
@ViewData.ModelMetadata.AdditionalValues["foo"]
</h3>
@foreach (var item in Model)
{
<div>
@item
</div>
}
結果:
![enter image description here](https://i.stack.imgur.com/r2G0C.png)
因此,大家可以看到我們添加的附加元數據顯示在模板中。
謝謝。正如我所提到的,如果我通過模板名稱,然後確實使用了正確的模板,則modelmetadata不能正確構建。我在AdditionalValues集合中擁有可從對象模板中看到的屬性的項目,但它們未通過。有任何想法嗎? – 2012-08-10 12:57:09
我不明白你有哪些屬性有額外的元數據。你能展示一些代碼嗎? – 2012-08-10 13:01:19
元數據位於集合屬性上。它是代碼中一個複雜的模板機制的一部分,但希望我添加到問題中會有所幫助。 – 2012-08-10 13:41:56