代码之家  ›  专栏  ›  技术社区  ›  Evan Davis

使用EditorFor()向MVC2中的集合动态添加项

  •  2
  • Evan Davis  · 技术社区  · 16 年前

    Editing a variable length list, ASP.NET MVC 2-style

    在帖子中,他提到可以用更少的代码使用Html.EditorFor()来完成,但由于索引的存在,这将更加困难。嗯,那正是我想做的,我不知道从哪里开始。

    我是一个ASP.NET新手,刚刚完成了书呆子晚餐教程,然后才投入到一个项目的工作,所以任何帮助将不胜感激。

    我希望生成从0开始的增量索引,而不是为集合中的每个项生成GUID。现在字段名看起来像“gifts[GUID].value”;我希望它们是“礼物[0]。价值”,“礼物” 1 .value”等,但我不明白集合是如何跟踪和生成这些索引的。

    2 回复  |  直到 16 年前
        1
  •  0
  •   Darin Dimitrov    16 年前

    首先定义一个编辑器模板( ~/Views/Shared/EditorTemplates/Gift.ascx ):

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyApp.Models.Gift>" %>
    <div class="editorRow">
        <% using(Html.BeginCollectionItem("gifts")) { %>
            Item: <%= Html.TextBoxFor(x => x.Name) %> 
            Value: $<%= Html.TextBoxFor(x => x.Price, new { size = 4 }) %> 
        <% } %>
    </div>
    

    RenderPartial 与…通话 EditorForModel

    <% using(Html.BeginForm()) { %>
        <div id="editorRows">
            <%= Html.EditorForModel() %>
        </div>
        <input type="submit" value="Finished" />
    <% } %>
    

    一旦你尝试了这个,你可能会回来问你是否有任何问题,解释症状。

        2
  •  1
  •   sonyisda1    13 年前

    为了响应您关于生成索引而不是guid的更新,最初的链接文章中有一些其他人的评论,他们试图解决相同的问题,但没有一个对我有用。我发现索引为的集合在以下位置被引用:

    html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix
    

    因此,我编写了一个helper函数来解析索引(如果有问题,那么将生成GUID)

    public static string GetCollectionItemIndex(this HtmlHelper html, string collectionName)
         {
         int idx;
         string sIdx;
    
         if (Int32.TryParse(Regex.Match(html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix, @"\d+").Value, out idx))
            {
            sIdx = idx.ToString();
            }
         else
            {
            sIdx = Guid.NewGuid().ToString();
            }
    
         return sIdx;
         }
    

    我编辑了BeginCollectionItem(..)函数,以便在设置项索引时调用此帮助程序函数:

         string itemIndex = idsToReuse.Count > 0 ? idsToReuse.Dequeue() : GetCollectionItemIndex(html, collectionName);