Asp.net mvc 调用EditorForModel(自定义对象模板)时未使用集合属性的EditorTemplate
我知道使用EditorForModel时通常不会呈现复杂类型,但我使用的是一个自定义对象模板,它不进行检查,并为每个属性(包括复杂类型)调用Html.Editor 不幸的是,虽然我可以在对象模板中看到属性的正确TemplateHint值,但编辑器调用似乎没有使用它,而是使用内置集合模板 我的对象模板基本上是这样的:Asp.net mvc 调用EditorForModel(自定义对象模板)时未使用集合属性的EditorTemplate,asp.net-mvc,asp.net-mvc-3,mvc-editor-templates,Asp.net Mvc,Asp.net Mvc 3,Mvc Editor Templates,我知道使用EditorForModel时通常不会呈现复杂类型,但我使用的是一个自定义对象模板,它不进行检查,并为每个属性(包括复杂类型)调用Html.Editor 不幸的是,虽然我可以在对象模板中看到属性的正确TemplateHint值,但编辑器调用似乎没有使用它,而是使用内置集合模板 我的对象模板基本上是这样的: @foreach (var property in ViewData.ModelMetadata.Properties.Where(x => x.ShowForEdit)) {
@foreach (var property in ViewData.ModelMetadata.Properties.Where(x => x.ShowForEdit))
{
@Html.Editor(property.PropertyName)
}
如果我通过将名称传递给编辑器调用来强制使用模板,则模板中的ModelMetadata为空
这是一个错误/有任何解决方法吗
更多信息:
因此,我的视图模型包含以下内容:
[ACustomAttribute("Something")]
public IEnumerable<int> SelectedOptions { get; set; }
[acutomattribute(“某物”)]
公共IEnumerable SelectedOptions{get;set;}
该属性实现IMetadataAware,并将一些内容添加到ModelMetadata的AdditionalValues集合中,以及设置TemplateHint。我可以从对象模板中读取此数据,但不能从自定义模板中读取
@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/editoremplates/nameoftypeofcollectionelements.cshtml
),并且在集合属性上使用了UIHint
,则:
[UIHint("FooBar")]
public IEnumerable<FooViewModel> Foos { get; set; }
型号:
public class MyViewModel
{
[ACustom("Something")]
public IEnumerable<int> Foos { get; set; }
}
视图(~/Views/Home/Index.cshtml
):
对象类型的编辑器模板(~/Views/Shared/EditorTemplates/object.cshtml
):
自定义编辑器模板(~/Views/Shared/EditorTemplates/Something.cshtml
):
@model IEnumerable
@ViewData.ModelMetadata.AdditionalValues[“foo”]
@foreach(模型中的var项目)
{
@项目
}
结果:
如您所见,我们添加的其他元数据显示在模板中。谢谢。正如我所提到的,如果我传递了模板名称,而它使用了正确的模板,那么modelmetadata就没有正确构建。我在属性的AdditionalValues集合中有可以从对象模板中看到的项,但它们没有传递。有什么想法吗?我不知道你在哪一个属性上有额外的元数据。您可以显示一些代码吗?元数据位于集合属性上。这是一个复杂的模板机制的一部分,很难使用代码,但希望我添加到问题中的内容能有所帮助。更新后的问题是否足够继续,或者您需要更多的代码?Thx@TheFlowerGuy,我仍然无法复制您的问题。我已经更新了我的答案。
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);
}
}
@model MyViewModel
@using (Html.BeginForm())
{
@Html.EditorForModel()
}
@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)
}
}
@model IEnumerable<int>
<h3>
@ViewData.ModelMetadata.AdditionalValues["foo"]
</h3>
@foreach (var item in Model)
{
<div>
@item
</div>
}