【发布时间】:2014-01-17 16:11:06
【问题描述】:
我在 MVC 中有一个名为 Entity 的模型,其中包含 Properties 并且这些属性的值可以是三件事之一。 Unit、DropDownSelection 或本机类型(int、string、datetime 等)。 Unit 和 DropDownSelection 非常简单,但它们的显示方式与原生类型不同(DropDownSelection -> DropDown、Native -> Input、Unit -> Input + DropDown)。
我个人基于 Property[0].DataType 知道,但我如何将该信息适当地传达给 Knockout,以便它在选择控件中显示 DropDownSelections、在输入中显示本机类型等。
当前视图
@model List<NMBS.EntityModels.Entity>
@* Page Content *@
<h1><span class="entity-type" data-bind="text: $data[0].EntityType"></span></h1>
<a data-bind="attr: { href: '/Entity/Create?EntityType=' + $data[0].EntityType() }" class="ignore">New</a>
<form>
<table>
<thead>
<tr data-bind="template: { name: 'HeaderRowTemplate', foreach: $data[0].Properties }">
<td data-bind="text: Name, visible: SummaryProperty"></td>
</tr>
</thead>
<tbody data-bind="template: { name: 'DataRowTemplate', foreach: $data }">
</tbody>
</table>
</form>
@* Templates *@
<script id="HeaderRowTemplate" type="text/html">
<td data-bind="text: Name, visible: SummaryProperty"></td>
</script>
<script id="DataRowTemplate" type="text/html">
<tr data-bind="template: { name: 'DataItemTemplate', foreach: Properties }"></tr>
</script>
<script id="DataItemTemplate" type="text/html">
<td data-bind="text: Value.ValueAsString, visible: SummaryProperty"></td>
</script>
@* Scripts *@
<script type="text/javascript">
function ApplyBindings() {
var data = @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model)),
viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
}
ApplyBindings();
</script>
实体属性
public Int32 ID { get; set; }
public String EntityType { get; set; }
public Int32? ParentID { get; set; }
public Int32? PropertyValueID { get; set; }
public List<Property> Properties { get; set; }
public Entities Children { get; set; }
public Boolean IsValueEntity { get; set; }
物业属性
public Int32 ID { get; set; }
public String Name { get; set; }
public String DataType { get; set; }
public Boolean Required { get; set; }
public Boolean OnlyOne { get; set; }
public Boolean ForceNew { get; set; }
public dynamic Value { get; set; }
public String ValueAsString { get; set; }
public Boolean SummaryProperty { get; set; }
问题:如何将数据绑定值(即 Entity[i].Property[i].Value)绑定到正确的 Html 控件?有没有办法显式或隐式告诉它为 DataType (Entity[i].Properties[i].DataType) 的某些值使用特定模板?
【问题讨论】:
标签: razor knockout.js knockout-mapping-plugin