0

I'm developing an app using ASP.NET Core MVC. In the app, there are many forms. The input sections in the forms consist of some HTML that is repeated a lot. For example, for a checkbox, we're using 13 lines of HTML and in a form, we might have tens of checkboxes. Each checkbox consists of labels and input tags and in those tags, we're using the asp-for tag helper. I was thinking that maybe we could use a partial view in order to only use one line per checkbox and limit duplication.

I tried something like this

Partial view:

@model object 

<div class="form-group form-md-checkboxes">
    <label asp-for="@Model" class="control-label col-md-3"></label>
    <div class="col-md-9 control-label">

        <div class="md-checkbox">
            <input asp-for="@Model" class="md-check" />
            <label asp-for="@Model">
                <span></span>
                <span class="check"></span>
                <span class="box"></span>

            </label>
        </div>
        <span asp-validation-for="@Model" class="text-danger"></span>
    </div>
</div>

In the form in the main razor page where the model contains multiple bool properties.

<form>
...
<partial name="_checkbox" for="BoolPropertyA" />
<partial name="_checkbox" for="BoolPropertyB" />
<partial name="_checkbox" for="BoolPropertyC" />
...
</form>

This doesn't seem to work properly, however. The Label doesn't get any text. Is what I'm trying to do at all possible? If so where am I going wrong?

Jackdaw
  • 7,626
  • 5
  • 15
  • 33
Fred
  • 187
  • 5
  • 23

1 Answers1

0

Here is a working demo:

Partial view(I use string as a model and repalce tag helpers with html code):

@model string
<div class="form-group form-md-checkboxes">
    <label for="@Model" class="control-label col-md-3" >@Model</label>
        <div class="col-md-9 control-label">

            <div class="md-checkbox">
                <input id="@Model" name="@Model" class="md-check" />
                <label for="@Model">
                    <span></span>
                    <span class="check"></span>
                    <span class="box"></span>

                </label>
            </div>
            <span class="text-danger field-validation-valid" data-valmsg-for="@Model" data-valmsg-replace="true"></span>
        </div>
    </div>

form:

<form id="form1" method="post" asp-action="Form2">
    @await Html.PartialAsync("_checkbox", "BoolPropertyA")
    @await Html.PartialAsync("_checkbox", "BoolPropertyA")
    @await Html.PartialAsync("_checkbox", "BoolPropertyA")
</form>

result:

enter image description here

Yiyi You
  • 16,875
  • 1
  • 10
  • 22
  • Not so bad, but I was hoping I could pass a reference to the property to the partial view. I have Display annotations on the properties that are picked up by the asp tag helpers. You will loose this if you just pass in the property as a string. You will also loose the special formatting that asp gives you based on the property type. – Fred Jun 16 '21 at 19:57