Scott Baker
Scott Baker

Reputation: 10443

ASP.NET Core Running Multiple Templates when using @Html.EditorForModel()

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.

Upvotes: 0

Views: 319

Answers (1)

Gonzalo Lorieto
Gonzalo Lorieto

Reputation: 645

What if you use the overload:

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

Upvotes: 0

Related Questions