如何从控制器调用EditorFor

Ser*_*gey 7 c# asp.net-mvc

我有位置列表

public class Location
{
    public string LocationName { get; set; }
    public string Address { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我为这个类创建了编辑器模板

<div>
   <span>@Html.TextBoxFor(a => a.LocationName)</span>
   <span style="color: red;">@Html.TextBoxFor(a => a.Address )</span>
</div>
Run Code Online (Sandbox Code Playgroud)

问题是,位置加载了ajax到我的页面,然后我将结果发送回服务器.但是如何使用特定索引获取此位置?我的意思是,对于第一个位置,它将生成如下:

<input type="text" name="Locations[0].LocationName" />
Run Code Online (Sandbox Code Playgroud)

对于第二个位置,当我按"添加位置"按钮时,它应该从服务器获取此位置(从控制器的操作作为html字符串)但索引1不是0,因为它是下一个位置.

有可能实现吗?或者我做错了什么?

arc*_*hil 3

像这样的东西

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

对于位置名称容器

<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>
Run Code Online (Sandbox Code Playgroud)

剩下的一小部分 javascript 可以在添加新索引时增加数据项计数并调用LocationNameEditorLocationNameEditor新索引的操作。