简体   繁体   中英

Keeping count within EditorTemplates

Is there a way when using EditorTemplates (With Lists) to work out the current list index value? For example in this Editor Template

@model myModel

<div class="email-box">
    @Html.TextBoxFor(x=>x.Email)
</div>

Can I work out what index in the List I am up to?

EDIt ====

View

 @model IEnumerable<myModel>

 @Html.EditorForModel()

Editor Template

@model myModel
<div class="email-box" rel="@ViewBag.Index">
    @Html.TextBoxFor(x => x.Email)
</div>

Custom Editor templates can accept values when called from the Html extension methods, these values are added to the ViewBag specifically for that view. You can use this to send the index of the element into that view

In the parent view

@{
    ViewBag.Title = "MyView";
    var index = 0;
}

<h2>My View</h2>

@foreach (var item in Model)
{
    <div>
        @Html.EditorFor(m => item, new { Index = index++ })
    </div>
}

In the editor template

@Html.TextBoxFor(m => string.Format("({0} - {1}", ViewBag.Index, m.Description)

I've actually solved this while looking around the available field options.

ViewData.TemplateInfo.HtmlFieldPrefix

Return [0], [1] etc.. Can just trim this down and we have the ID.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM