2

In my model I have a List property of a complex type called EventField.

I created an editor template, which works fine using:

@Html.EditorFor(e => e.EventField)

My question is, within that Editor template I want to pick out the index/sequence number on its own, as a number. This index will simply be added into the template as a data attribute so I can pick it up using javascript.

A couple of answer are out there that don't suffice:

  1. @html.IdFor - outputs the whole name e.g Name[0].other
  2. here - you can't pass through the model name "EventField" this way.

Is there a simple method/function/helper that will give me access to that Index, without having to change how I call the Editor template?

Community
  • 1
  • 1
Ian
  • 2,898
  • 1
  • 27
  • 29
  • 1
    The value of the index if encapsulated with in the helper method and you don't have access to it. But is this really necessary. You can easily use jquery to get the index of a DOM element within its container. –  Mar 04 '15 at 19:38
  • Thanks Stephen, jQuery's .Index was new to me and makes the whole job very easy. It would be nice to know if there is an answer to the question though as I thought it would be simple property to access. – Ian Mar 05 '15 at 20:18
  • The simple answer is no. A html helper is an extension method that outputs html (`MvcHtmlString`). It has no properties you can access. –  Mar 05 '15 at 21:05

1 Answers1

1

How about:

@using System
@using System.Text.RegularExpressions

var i = Convert.ToInt32(Regex.Matches(
         ViewData.TemplateInfo.HtmlFieldPrefix,
         @"\[([0-9]+)?\]")[0].Groups[1].ToString());
Ryan Penfold
  • 752
  • 2
  • 11
  • 16