2014-09-30 71 views
0

型號:允許使用添加項目到模型asp.net mvc4

public class oPage 
{ 
    public int PageId { get; set; } 
    public List<oContent> Contents { get; set; } 
} 

oContent對象具有的屬性:標識文本

的觀點:(剃刀)

@for (int i = 0; i <= Model.Agrees.Count; i++) 
{ 
    @Html.TextAreaFor(m => Model.Agrees[i].Text) 
} 

我想讓用戶添加從客戶端的另一個內容。

我找到了一些解決方案,我不喜歡:

  1. 手動編寫HTML標記。我不喜歡它,因爲也許在某一天渲染的結構會改變,我的代碼也不會說話。 (Like here:http://www.techiesweb.net/asp-net-mvc3-dynamically-added-form-fields-model-binding/

  2. 從服務器獲取結構。我不喜歡這個,因爲..以及我總是寧願不使用服務器,除非我必須。 (喜歡這裏:How to add items to MVC model in javascript?

我正在尋找一個更好的,更聰明的解決方案。

+0

我不同意你的理由不遵循這些文章。 – CSharper 2014-09-30 12:41:02

+0

爲什麼不能?你能解釋一下嗎? – 2014-09-30 13:04:00

+0

您將使用HTML即將完成的小DOM操作。添加一個新的表格行,在可預見的將來我沒有看到它會在哪裏破壞你的代碼,HTML是非常標準的。關於第二點,如服務器添加新項目沒有任何問題,如文章 – CSharper 2014-09-30 13:09:52

回答

0

解決方案有點複雜,但我認爲它涵蓋了我所有的觀點。

的邏輯是:

  1. 從剃刀引擎

    @Html.TextAreaFor(m => Model.Agrees[i].Text).ToHtmlString() 
    
  2. 獲取HTML比替換屬性名稱和ID索引號(它更有意義不是依靠所有屬性值)

    public static string CreateHelperTemplate(string PlaceholderPerfix, MvcHtmlString mvcHtmlString) 
    { 
        string Result = ""; 
        XElement TempNode = XDocument.Parse(mvcHtmlString.ToHtmlString()).Root; 
    
        XAttribute AttrId = TempNode.Attribute("id"); 
        AttrId.Value = AttrId.Value.Replace("0", PlaceholderPerfix); 
    
        XAttribute AttrName = TempNode.Attribute("name"); 
        AttrName.Value = AttrName.Value.Replace("0", PlaceholderPerfix); 
    
        // Clear the content if exist 
        TempNode.SetValue(string.Empty); 
    
        Result = TempNode.ToString(); 
    
        return Result; 
    } 
    
  3. 結果它有點像這樣的:

    <textarea class="form-control" cols="20" id="Perfix_$__Text" name="Agrees[$].Text" rows="2"></textarea> 
    
  4. 然後,在JavaScript中,當「添加項」按鈕,就可以得到「模板」和索引和替換「$」與用戶點擊該指數。

所以,我並不需要調用服務器,如果輔助的結構會改變我的代碼仍然可以工作。

它的工作。

相關問題