mvc4 get List index in editor template

1.2k views Asked by At

For my project i need to know the index of the list element in an editor template to give this to a delete button.

For example i have a Model:

public class Model
{
    public int ID { get; set; }
    public List<TemplateModel> Words { get; set; }
    public Model()
    {
    }
}

a second Model with:

  public class TemplateModel
    {
        public int secondID { get; set; }
        public string word { get; set; }
        public TemplateModel()
        {
        }
    }

a View with:

@Html.EditorFor(m=>m.Words)

and a template with:

    @model TemplateModel
<p>@Html.TextBoxFor(m=>m.word)</p>
<p>@Html.TextBoxFor(m=>m.secondId)</p>
<p><input type="button" name="Index should be here"></p>

is it possible to get the index from the list for the button? mvc automatically created names like Words[index] but how is it transmitting the index and is it possible to use him?

Update: I found a solution: In the CiewContext is a method to build the names of the elements. So it is also able use this and attach an own string. So i implement this in the editor template:

<input type="button" name="@ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName("Delete")"/>

and in html it will look like

<input type="button" name="Words[0].Delete">
1

There are 1 answers

2
Syneryx On

In your template for the List<TemplateModel> try the following.

@model List<TemplateModel>

@for (var i = 0; i < Model.Count(); i++)
{
    <p>@Html.TextBoxFor(m => m[i].Word)</p>
    <p>@Html.TextBoxFor(m => m[i].SecondId)</p>
    <p><input type="button"  name="@(i)"></p>
}