2010-07-12 81 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