EditorFor的IEnumerable< T>与TEMPLATENAME [英] EditorFor IEnumerable<T> with TemplateName

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

问题描述

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

公共类分类
{
    ...
    公共IEnumerable的<产品与GT;产品{搞定;组; }
}

查看:

@model类别
...
< UL>
    @ Html.EditorFor(M = GT; m.Products)
< / UL>

EditorTemplate:

@model产品
...
<立GT;
    @ Html.EditorFor(M = GT; m.Name)
< /李>

请注意,我没有定义的IEnumerable&LT的EditorTemplate;产品> ,我只能创建它的产品模式,MVC框架是足够聪明的利用了自己的模板IEnumerable的。它通过迭代,我的收藏​​,并要求我EditorTemplate。

输出的HTML将是这样的

...
<立GT;
    <输入ID =Products_i_NameNAME =产品[I] .Name点类型=文本VALUE =SomeName>
< /李>

我可以毕竟张贴到我的控制器。

但为什么不MVC做的伎俩,当我定义EditorTemplate一个模板名称?

@ Html.EditorFor(M = GT; m.Products,ProductTemplate)

在这种情况下,我必须为属性的类型更改为的IList<产品> ,由我自己通过收集迭代,并调用EditorTemplate

@for(INT I = 0; I< Model.Products.Count;我++)
{
    @ Html.EditorFor(M => m.Products [I]中,ProductTemplate)
}

这似乎有点脏的解决方法给我。这是任何其他的,清洁的解决方案要做到这一点?


解决方案

  

这是任何其他的,清洁的解决方案要做到这一点?


简单的答案是否定的,它吸收不好,我完全同意你的观点,但是这就是框架的设计者决定如何实现此功能。

所以,我做的是我坚持的约定。由于我为每个这不是什么大不了的事有一个相应的编辑器模板的意见和谐音特定视图模型,命名方式相同集合类型。

Suppose I have a simple model to explain the purpose:

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

View:

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

EditorTemplate:

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

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.

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.

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

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

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&LT; T&GT;与TEMPLATENAME的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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