0

I have an EditorTemplate for booleans:

@model bool?
<div class="form-group">
    <div class="custom-control custom-checkbox ">
        <input asp-for="@Model"/>
        <label asp-for="@Model"></label>
    </div>
</div>

and I have a Model similar to this:

public class FooModel
{
    public bool IsFoo { get; set; }
    public bool IsBar { get; set; }
    public bool IsBaz { get; set; }
}

When I try to render the templates individually for the properties

@Html.EditorFor(m => m.FooModel.IsFoo)
@Html.EditorFor(m => m.FooModel.IsBar)
@Html.EditorFor(m => m.FooModel.IsBaz)

...I get what I'm expecting:

Screenshot of expected

<div class="form-group">
  <div class="custom-control custom-checkbox ">
     <input type="checkbox" data-val="true" data-val-required="The IsFoo field is required." id="FooModel_IsFoo" name="FooModel.IsFoo" value="true"> 
     <label for="FooModel_IsFoo">IsFoo</label>
  </div>
</div>
<!-- same for IsBar and IsBaz -->

... but when I try to take a "shortcut" and let the framework handle it

@Html.EditorForModel() //  model is FooModel

I get all kinds of weirdness. The labels are "doubled up" because (I believe) the framework is running its own template and my template.

Screenshot of unexpected result

<div class="editor-label">
  <label for="CsosTypeFilter_IsFoo">IsFoo</label>
</div>
<div class="editor-field">
  <!-- contents of my template are here, removed for brevity --> 
  <span data-valmsg-for="CsosTypeFilter.IsFoo" 
        data-valmsg-replace="true" 
        class="field-validation-valid">
  </span>
</div>
<!-- same for IsBar and IsBaz -->

Anyone know what I'm doing wrong and how to fix this? Any assistance is appreciated.

Scott Baker
  • 10,013
  • 17
  • 56
  • 102
  • `Html.EditorForModel()` is really only useful for basic scaffolding. The only way to make it work for a custom template is to define an editor template for the entire class, which pretty much defeats the purpose. – Chris Pratt Aug 26 '19 at 17:34

1 Answers1

0

What if you use the overload:

@Html.EditorForModel(m => m, "template") // model is FooModel, template is your template

Gonzalo Lorieto
  • 635
  • 6
  • 24
  • I don't have a template defined for `FooModel`, just for the `boolean` properties. If I define a template for `FooModel`, then I'm just moving all the code I'm still manually writing the `@Html.EditorFor(m => m.IsFoo) ...` to another file vs. getting rid of it entirely. – Scott Baker Aug 26 '19 at 17:31
  • I missunderstood the question. Check this link https://stackoverflow.com/questions/15092998/how-should-i-call-editorformodel-with-its-parameters – Gonzalo Lorieto Aug 26 '19 at 17:58