简体   繁体   中英

Find index of EditorFor template

I have an EditorFor template that looks like this,

@{
Layout = null;

@Html.EditorFor(model => model.Name)
@Html.EditorFor(model => model.Value)

}

for a List of Key/Value pairs. Here is the Model.

public List<NameValuePair> Parameters { get; set; }

This produces a list of editable boxes. I need to delete a particular element (so when the page refreshes the whole "row" is gone). I am having trouble finding the index of that element to pass to the delete function in my controller. Is there an easy way to find a particular index in a EditorFor template?

Update--

This is what the code in the view looks like. Which displays the list of parameters.

@Html.LabelFor(model => model.Parameters)
@Html.EditorFor(model => model.Parameters)
    <input type="submit" name="command" value="addParam" class="btn btn-default btn-primary" />

And this is what the delete method I am attempting to use in the controller looks like.

public ActionResult DeleteParamaters(long id, int index)
    {
        var templateStep = Biz.GetTemplateStep(id);

        templateStep.Parameters.RemoveAt(index);
        return View("CreateTemplateStep", templateStep);
    }

My end goal is a delete button next to each list item, and when clicked will delete that particular item from the list.

You can pass an additionalViewValues object to the EditorFor function.

An anonymous object that can contain additional view data that will be merged into the ViewDataDictionary instance that is created for the template.

So when you iterate over your list and renders the editor for each then you can pass any data to the template and so you can send it to the controller to identify your data.

There are couple of examples on SO about how to use additional data across templates. For example: Pass Additional ViewData to a Strongly-Typed Partial View

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