EditorFor IEnumerable<T>;带模板名称 [英] EditorFor IEnumerable&lt;T&gt; with TemplateName

查看:22
本文介绍了EditorFor IEnumerable<T>;带模板名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个简单的模型来解释目的:

Suppose I have a simple model to explain the purpose:

public class Category
{
    ...
    public IEnumerable<Product> Products { get; set; }
}

查看:

@model Category
...
<ul>
    @Html.EditorFor(m => m.Products)
</ul>

编辑器模板:

@model Product
...
<li>
    @Html.EditorFor(m => m.Name)
</li>

请注意,我不必为 IEnumerable 定义 EditorTemplate,我只能为 Product 模型创建它,并且 MVC 框架足够智能使用它自己的 IEnumerable 模板.它遍历我的集合并调用我的 EditorTemplate.

Note that I don't have to define the EditorTemplate for IEnumerable<Product>, I can only create it for the Product model and MVC framework is smart enough to use its own template for IEnumerable. It iterates through my collection and calls my EditorTemplate.

输出 html 将是这样的

The output html will be something like this

...
<li>
    <input id="Products_i_Name" name="Products[i].Name" type="text" value="SomeName">
</li>

毕竟我可以发布到我的控制器.

which I can post to my controller after all.

但是当我用模板名称定义 EditorTemplate 时,为什么 MVC 没有起作用?

But why doesn't the MVC do the trick when I define EditorTemplate with a template name?

@Html.EditorFor(m => m.Products, "ProductTemplate")

在那种情况下,我必须将属性的类型更改为 IList,自己遍历集合并调用 EditorTemplate

In that case I have to change the type of the property to IList<Product>, iterate through the collection by myself and call the EditorTemplate

@for (int i = 0; i < Model.Products.Count; i++)
{
    @Html.EditorFor(m => m.Products[i], "ProductTemplate")
}

这对我来说似乎是一种肮脏的解决方法.有没有其他更干净的解决方案来做到这一点?

which seems kind of dirty workaround to me. Is it any other, cleaner solution to do this?

推荐答案

还有其他更简洁的解决方案吗?

Is it any other, cleaner solution to do this?

简单的答案是否定的,它很糟糕,我完全同意你的看法,但这就是框架设计者决定实现此功能的方式.

The simple answer is no, it sucks badly, I completely agree with you, but that's how the designers of the framework decided to implement this feature.

所以我所做的就是遵守约定.由于我对每个视图和局部视图都有特定的视图模型,因此拥有相应的编辑器模板并没有什么大不了的,其命名方式与集合的类型相同.

So what I do is I stick to the conventions. Since I have specific view models for each views and partials it's not a big deal to have a corresponding editor template, named the same way as the type of the collection.

这篇关于EditorFor IEnumerable<T>;带模板名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆