【问题标题】:Dynamically add items to a collection in MVC2 using EditorFor()使用 EditorFor() 将项目动态添加到 MVC2 中的集合
【发布时间】:2011-03-15 00:15:03
【问题描述】:
我正在尝试这样做:Editing a variable length list, ASP.NET MVC 2-style
在帖子中,他提到使用 Html.EditorFor() 可以用更少的代码完成,但由于索引的原因,这会更加困难。嗯,这正是我想做的,我不知道从哪里开始。
我是一名 ASP.NET 新手,刚刚完成了 Nerd Dinner 教程,然后才开始投入工作中的项目,因此我们将不胜感激。
更新 1: 我不想为集合中的每个项目生成 GUID,而是生成从 0 开始的增量索引。现在字段名称看起来像“gifts[GUID].价值”;我希望它们成为 "gifts[0].value","gifts1.value" 等,但我不明白该集合如何跟踪并生成这些索引。
【问题讨论】:
标签:
asp.net
asp.net-mvc-2
asp.net-ajax
【解决方案1】:
为了响应您关于生成索引而不是 GUID 的更新,原始链接文章有一些来自其他人的 cmets 试图解决相同的问题,但没有一个对我有用。我发现带有索引的集合在以下位置被引用:
html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix
所以我写了一个辅助函数来解析索引(如果有问题,则会生成 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);
希望这对其他人有帮助!
【解决方案2】:
好吧,您首先定义一个编辑器模板 (~/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" />
<% } %>
一旦你尝试过这个,你可能会回来通过解释症状来询问你是否有任何问题。