如何为ASP.NET Core制作精美的复选框模板? [英] How can I make a fancy checkbox template for ASP.NET Core?

查看:134
本文介绍了如何为ASP.NET Core制作精美的复选框模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型中有很多 boolean ,并且我们使用的是Bootstrap,因此对于每个布尔属性,我都进行复制/粘贴重构: / p>

I've got a lot of booleans 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.


  1. 我在这里做错了什么 将模板命名为 boolean.cshtml

  2. ViewData.TemplateInfo.FormattedValue 正确的值,以获取 Display(Name = xxx)属性的属性 不。 ViewData.ModelMetadata.DisplayName

  3. 是否有一些新的&改进的版本而不是我应该使用的ASP.NET Core中的编辑器模板(例如Tag Helpers?),而不是旧方式;如果是这样,我该如何处理?

  1. what am I doing wrong here name the template 'boolean.cshtml'
  2. is ViewData.TemplateInfo.FormattedValue the right value to get the Display(Name="xxx") Attribute from the property nope. ViewData.ModelMetadata.DisplayName
  3. 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制作精美的复选框模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆