使用@
Html.EditorFor(model => model.IsClient),其中IsClient是一个布尔值,使用Not Set,Yes和No作为选项呈现下拉列表.
一切都很好.
现在我想将knockoutjs与我喜欢的结果下拉列表一起使用,那么如何使用@ Html.EditorFor添加data-bind属性,我需要使用knockoutjs来处理这个下拉列表?
我试过了:
@Html.EditorFor(model => model.IsClient,new Dictionary<string,object> { { "data-bind","value: Account.IsClient" } })
但是,它使用对象additionalViewData参数,并且它不呈现data-bind属性.这可能很自然,因为此参数可能与渲染标记的Html属性无关.
但是,找不到任何合理的文档,并且没有其他重载看起来可能是我想要的候选者.
TIA有什么建议.
解决方法
关于ASP.NET MVC 2中的显示和编辑器模板的Brad Wilson
blogged所以你可以修改boolean的默认模板并添加你需要的属性(〜/ Views / Shared / EditorTemplates / MyTemplate.cshtml):
@{ bool? value = null; if (ViewData.Model != null) { value = Convert.ToBoolean(ViewData.Model,System.Globalization.CultureInfo.InvariantCulture); } var triStateValues = new List<SelectListItem> { new SelectListItem { Text = "Not Set",Value = String.Empty,Selected = !value.HasValue },new SelectListItem { Text = "True",Value = "true",Selected = value.HasValue && value.Value },new SelectListItem { Text = "False",Value = "false",Selected = value.HasValue && !value.Value },}; } @if (ViewData.ModelMetadata.IsNullableValueType) { <!-- TODO: here you can use any attributes you like --> @Html.DropDownList( "",triStateValues,new { @class = "list-Box tri-state",data_bind="value: " + ViewData.TemplateInfo.GetFullHtmlFieldName("") // you could also use ViewData.ModelMetadata.PropertyName if you want to get only the property name and not the entire navigation hierarchy name } ) } else { @Html.CheckBox("",value ?? false,new { @class = "check-Box" }) }
最后:
@Html.EditorFor(model => model.IsClient,"MyTemplate")
或使用UIHint属性修饰视图模型上的IsClient属性:
[UIHint("MyTemplate")] public bool? IsClient { get; set; }
然后:
@Html.EditorFor(x => x.IsClient)