簡體   English   中英

我如何在MVC4的編輯器模板中綁定字段以剔除?

[英]How can I bind fields to knockout in an Editor Template in MVC4?

在我的MVC4項目中,我有一個類別視圖模型和一個產品視圖模型集合。 我使用編輯器模板來呈現單個產品視圖模型,並將產品視圖模型的集合傳遞給它:

類別視圖模型:

@model CategoryViewModel
@using MVC4PartialViews.Models.ViewModels

<div class="editor-field">
    @Html.EditorFor(model => model.CategoryName)
    @Html.ValidationMessageFor(model => model.CategoryName)
</div>

@Html.EditorFor(x => x.Products)

呈現集合中每個產品的編輯器模板:

<div class="editor-field">
    @Html.EditorFor(model => model.ProductName)
    @Html.ValidationMessageFor(model => model.ProductName)
</div>
// etc.

這非常有效,因為它會自動正確地命名和索引元素,因此所有產品都將作為父“類別”視圖模型的一部分回發-這是它的輸出:

<div class="editor-field">
    <input class="text-box single-line" id="Products_0__ProductName" name="Products[0].ProductName" type="text" value="Add 1st product for this Category" />
    <span class="field-validation-valid" data-valmsg-for="Products[0].ProductName" data-valmsg-replace="true"></span>
</div>

如何綁定編輯器模板中的字段以進行剔除? 我可以以某種方式訪問​​或使用編輯器模板用來命名元素的索引值嗎? 我可以在父級(類別)視圖模型中綁定字段,如下所示:

<script>
    window.defaultCategory = @Html.Raw(Json.Encode(Model));
</script>

@Html.TextBoxFor(
    model => model.CategoryName,
    new Dictionary<string, object>
    {
        {"style", "width: 30%;"},
        {"placeholder", "Please enter the Category name"},
        { "data-bind", "value: currentCategory.CategoryName" }
    })

我需要生成如下內容,其中[n]是編輯器模板在呈現產品集合中的每個產品時所產生的索引值:

{ "data-bind", "value: currentCategory.Products[n].ProductName" }

還是應該像這樣:

{ "data-bind", "value: currentCategory.Products()[n].ProductName" }

所有幫助或想法表示贊賞:)

您可以從TemplateInfo中提取當前索引:

@model ProductViewModel

<div class="editor-field">    
    @Html.TextBoxFor(
        model => model.ProductName,
        new {
            style = "width: 30%;",
            placeholder = "Please enter the Category name",
            data_bind = string.Format(
                "value: currentCategory.{0}.ProductName",
                ViewData.TemplateInfo.HtmlFieldPrefix
            )
        }
    )
    @Html.ValidationMessageFor(model => model.ProductName)
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM