2010-07-12 75 views
2

我试图做到这一点:Editing a variable length list, ASP.NET MVC 2-style动态使用EditorFor()在MVC2项目添加到收藏

在他提到,它可以使用Html.EditorFor()更少的代码完成后,但由于这些指标会更加困难。那么,这正是我想要做的,我不知道从哪里开始。

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

更新1:代替生成一个GUID为集合中的每一个项目,我想产生增量索引以0开始眼下的字段名看起来像“礼物[GUID] .value的”;我想他们是“礼物[0] .value”,“礼物1。价值”等,但我不明白如何收集保持跟踪并产生这些指数。

回答

0

那么,你首先定义一个编辑模板(~/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" /> 
<% } %> 

一旦你尝试了这一点,你可能会回来并通过解释症状询问您是否有任何问题。

+0

谢谢!我已经更新了有关我现在位置的详细信息摘要。 – Mathletics 2010-07-13 14:54:03

1

为了响应您关于生成索引而不是GUID的更新,原始链接文章从其他人那里获得了一些旨在解决相同问题的评论,但他们都没有为我工作。我发现与指数集合在以下位置被引用:

html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix 

所以我写了一个辅助函数解析出指数(如果有,则GUID将产生一个问题)

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

希望这可以帮助其他人:

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(..)函数来调用这个辅助函数!

+0

谢谢。你没有在你的函数中使用collectionName。 – 2014-04-09 00:14:01