问题描述
我的模型中有很多 boolean
,并且我们使用的是Bootstrap,因此对于每个布尔属性,我都进行复制/粘贴重构: / p>
I've got a lot of boolean
s in my model, and we're using Bootstrap, so for every boolean property I'm copy/paste refactoring:
<div class="form-group">
<div class="custom-control custom-checkbox ">
<input asp-for="IsFoo"/>
<label asp-for="IsFoo"></label>
</div>
</div>
...但是那真是愚蠢。我尝试将其添加到视图/共享/EditorTemplates/bool.cshtml
:
... but that's dumb. I tried adding this to Views/Shared/EditorTemplates/bool.cshtml
:
@model bool?
<div class="form-group">
<div class="custom-control custom-checkbox ">
<input asp-for="@Model"/>
<label asp-for="@ViewData.TemplateInfo.FormattedModelValue"></label>
</div>
</div>
...并用 @ Html.EditorFor(m => ; m.IsFoo)
,但我得到的只是默认模板中的 input
元素。
... and calling it with @Html.EditorFor(m => m.IsFoo)
but all I'm getting back is a plain input
element from the default template.
- 将模板命名为 boolean.cshtml
- 不。
ViewData.ModelMetadata.DisplayName
- 是否有一些新的&改进的版本而不是我应该使用的ASP.NET Core中的编辑器模板(例如Tag Helpers?),而不是旧方式;如果是这样,我该如何处理?
- name the template 'boolean.cshtml'
- nope.
ViewData.ModelMetadata.DisplayName
- is there some new & improved version instead of Editor Templates in ASP.NET Core that I should be using (like Tag Helpers?) instead of the "old" way, and if so, how do I go about it?
推荐答案
使用< partial>
标记帮助程序:
<partial name="MyCheckbox" for="IsFoo" />
它也具有绑定属性:
class MyModel
{
public List<MyCheckboxModel> MyCheckboxList { get; set; }
}
class MyCheckboxModel
{
public Boolean IsChecked { get; set; }
}
@for( Int32 i = 0; i < this.Model.MyCheckboxList.Count; i++ )
{
<partial name="MyCheckbox" for="MyCheckboxList[i]"
}
将部分视图更改为:
@model MyCheckboxModel
<div class="form-group">
<div class="custom-control custom-checkbox">
<input asp-for="@Model"/>
<label asp-for="@Model"></label>
</div>
</div>
for =
属性导致名称中的name / id / binding上下文以匹配named属性,因此ASP.NET将尽力确保< input asp-for = @ Model />
将对应于 Model.MyCheckBoxList [0]
,依此类推。
The for=""
attribute causes the name/id/binding context in the partial to match the named property, so ASP.NET will do the magic to ensure that <input asp-for="@Model" />
will correspond to Model.MyCheckBoxList[0]
and so on.
这篇关于如何为ASP.NET Core制作精美的复选框模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!