How can I call EditorFor from the controller

asp.net-mvc, c#

Solution

Something like this

    [HttpGet]
    public virtual ActionResult LocationEditor(int index)
    {
        ViewData.TemplateInfo.HtmlFieldPrefix = string.Format("Locations[{0}]", index);
        return PartialView(@"EditorTemplateExplicitPathAsOnlyViewNameAintGonnaWork.cshtml");
    }

And for location names container

<div class="locations-container" data-item-count="@Model.Count">
    @for (int j = 0; j < Model.Count; j++)
    {
        @Html.EditorFor(model => model[j])
    }
    <a href="#" class="add-location">Add Location</a>
</div>

The rest of tiny bit of javascript to increment data-item-count upon adding and call `LocationNameEditorLocationNameEditor` action with new index is upon you.

Problem

I have list of locations ``` public class Location { public string LocationName { get; set; } public string Address { get; set; } } ``` I created editor template for this class ``` <div> <span>@Html.TextBoxFor(a => a.LocationName)</span> <span style="color: red;">@Html.TextBoxFor(a => a.Address )</span> </div> ``` The problem is that locations load with ajax to my page and then I am going to send the results back to the server. But how to get this location with specific index? I mean that for the first location it will generate like this: ``` <input type="text" name="Locations[0].LocationName" /> ``` For the second location when I press "Add Location" button it should get this location from the server (from action of controller as html string) but with index 1 not 0 because it is next location. Is it possible to achieve it? Or I am doing something wrong?

Original source