Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping count within EditorTemplates

Tags:

c#

asp.net-mvc

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>
like image 278
LiamB Avatar asked Dec 14 '25 16:12

LiamB


2 Answers

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)
like image 103
Jay Avatar answered Dec 17 '25 07:12

Jay


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.

like image 41
LiamB Avatar answered Dec 17 '25 07:12

LiamB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!