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.

1
  • 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. Commented Aug 26, 2019 at 17:34

1 Answer 1

0

What if you use the overload:

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
I missunderstood the question. Check this link stackoverflow.com/questions/15092998/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.