在MVC中显示模板当前项目的索引 [英] Index of current item in mvc display template

查看:136
本文介绍了在MVC中显示模板当前项目的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个displaytemplate一个MVC页面。
我如何获得当前项目的索引中displaytemplate正在呈现。
它产生的名称属性绑定正确的结果。

 <输入名称=XXX [0] .FirstName/>
<输入名称=XXX [1] .FirstName/>

我要在显示模板索引值。它是在ViewContext地方?

@ * page.cshtml的 @
@model ... @
的财产联系人是IEnumerable的* @

 <表ID =接触级=编辑>
    <&THEAD GT;
    < TR><第i个姓名和LT; /第i个百分位>姓< /第i个百分位>联系方式< /第i< / TR>
    < / THEAD>    <&TBODY GT;
    @ Html.DisplayFor(X => x.Contacts)
    < / TBODY>

在显示模板,我们有

  @ * contact.cshtml * @
@model ...... @ *这是IEnumerable的&LT的笔; T> * @&所述; TR>
   @ *我需要的当前迭代的索引HERE * @
   < TD> @ Html.DisplayFor(X => x.FirstName)LT; / TD>
< / TR>


解决方案

恐怕没有简单的方法来获得索引。它埋在内部 System.Web.Mvc.Html.DefaultDisplayTemplates.CollectionTemplate 方法内,不外露。你可以使用是场preFIX:

  @ ViewData.TemplateInfo.HtmlField preFIX

另一种可能性是将 @ Html.DisplayFor(X => x.Contacts)

  @for(INT I = 0; I< Model.Contacts.Length;我++)
{
    @ Html.DisplayFor(X => x.Contacts [I],新{指数= I})
}

,然后在模板中 @ ViewBag.Index 应该给你目前的索引,但我必须承认它有点难看。

I have an mvc page with a displaytemplate. How do I get the index of the current item being rendered in the displaytemplate. it produces correct bindable results in the name attributes.

<input name="xxx[0].FirstName"/>
<input name="xxx[1].FirstName"/>

I want that index value in the display template. Is it in the ViewContext somewhere?

@* page.cshtml @ @model ...@ property Contacts is IEnumerable *@

<table id="contacts" class="editable">
    <thead>
    <tr><th>Name</th><th>Surname</th><th>Contact Details</th></tr>
    </thead>

    <tbody>
    @Html.DisplayFor(x => x.Contacts)
    </tbody>

in the display template we have

@* contact.cshtml *@
@model ...@* This is the T of the IEnumerable<T> *@

<tr>
   @* I NEED THE INDEX OF THE CURRENT ITERATION HERE *@
   <td>@Html.DisplayFor(x => x.FirstName)</td>
</tr>

解决方案

I am afraid there is no easy way to get the index. It's buried inside the internal System.Web.Mvc.Html.DefaultDisplayTemplates.CollectionTemplate method and not exposed. What you could use is the field prefix:

@ViewData.TemplateInfo.HtmlFieldPrefix

Another possibility is replace @Html.DisplayFor(x => x.Contacts) with:

@for (int i = 0; i < Model.Contacts.Length; i++)
{
    @Html.DisplayFor(x => x.Contacts[i], new { Index = i })
}

and then inside the template @ViewBag.Index should give you the current index but I must admit it's kinda ugly.

这篇关于在MVC中显示模板当前项目的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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