在我的MVC4项目中,我有一个带有Product视图模型集合的Category视图模型。我使用编辑器模板渲染单个产品视图模型,并将Product视图模型的集合传递给它:
类别视图模型:
@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>
如何将Editor模板中的字段绑定到knockout?我可以以某种方式访问或使用编辑器模板用于命名元素的索引值吗?我可以在父(类别)视图模型中绑定字段没有问题,如下所示:
<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]是编辑器模板生成的索引值,因为它在Products集合中呈现每个产品:
{ "data-bind", "value: currentCategory.Products[n].ProductName" }
或者它应该是这样的:
{ "data-bind", "value: currentCategory.Products()[n].ProductName" }
所有帮助或想法都赞赏:)
答案 0 :(得分:1)
您可以从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>