本文介绍了如何访问模型财产的IEnumerable类型的Razor视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何访问Model属性(如 @ Html.EditorFor(X => Model.Name))的IEnumerable的类型的Razor视图,而不使用循环?也就是说,如果视图是强类型的某些型号拿着型号为列表。
例如。

How to access Model property(Like @Html.EditorFor(x=>Model.Name)) in Razor view of IEnumerable Type without using Loops??I.e If a view is strongly typed to some Model holding Model as a LIST.
Eg.

@model IEnumerable<EFTest2.DAL.package_master>


然后就是可以显示TestBoxFor或EditorFor不使用foreach循环(创建新模型)的HTML帮助。???


Then is it possible to Display TestBoxFor or EditorFor (to create new Model) Html helper without using foreach Loop.???

推荐答案

在某些型号的属性类型的IEnumerable&LT; SOMETYPE&GT; 你通常会定义一个编辑/显示模板(〜/查看/共享/ EditorTemplates / SomeType.cshtml 〜/查看/共享/ DisplayTemplates / SomeType.cshtml )。这个模板会自动呈现的集合中的每个元素,这样你就不需要写循环:

When some model property is of type IEnumerable<SomeType> you would normally define an editor/display template (~/Views/Shared/EditorTemplates/SomeType.cshtml or ~/Views/Shared/DisplayTemplates/SomeType.cshtml). This template will be automatically rendered for each element of the collection so that you don't need to write loops:

@Html.EditorFor(x => x.SomeCollection)

和在模板中,你将能够访问各个属性:

and inside the template you will be able to access individual properties:

@model SomeType
@Html.EditorFor(x => x.Name)
...

现在,如果你绝对需要直接访问某些元素,它是强类型为的IEnumerable℃的视图中; SOMETYPE&GT; 你最好使用一些其他的集合类型,如的IList&LT; SOMETYPE&GT; SOMETYPE [] 作为视图模式,这将给你的元素直接访问通过索引,你会能够例如这样做是为了访问集合的第6元素:

Now, if you absolutely need to directly access some element inside a view which is strongly typed to IEnumerable<SomeType> you would better use some other collection type such as IList<SomeType> or SomeType[] as view model which will give you direct access to elements by index and you will be able to do this for example to access the 6th element of the collection:

@model IList<SomeType>
@Html.EditorFor(x => x[5].Name)

这篇关于如何访问模型财产的IEnumerable类型的Razor视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 02:32