Bootstrap 5 - Floating Labels with Razor syntax

625 Views Asked by At

Hopefully this is an easy one...

I am having an issue with Bootstrap 5 floating labels not working when I create HTML elements using Razor syntax.

If I use plain HTML they work as expected. Using razor the labels are appearing in the state you'd expect if the text box has focus (top left of input)

<div class="form-floating mb-3">
   @Html.EditorFor(model => model.Recipient, new { htmlAttributes = new { @class = "form-control", @onchange = "javascript: Changed( this, 'recipient-name' );" } })
   @Html.ValidationMessageFor(model => model.Recipient, "", new { @class = "text-danger" })
   @Html.LabelFor(model => model.Recipient)
</div>

Here is an image of the above on load - Code output in UI

Has anyone had this issue, know a way to get around it or spot what I am doing wrong? (I need the input tag to be populated from the model as the form can be used to create a new request or update and existing request)

Thanks

2

There are 2 best solutions below

0
MLH On BEST ANSWER

Thanks but I figured out what I was doing wrong. The issue was simple...

ISSUE - There was no placeholder tag which this animation relies on.

RESOLUTION - Add @placeholder = "Recipient Name"

To provide a bit more info the text input looks different when in focus/not focused. This was the issue.

It should have looked like this when not focused - Not Focused

But it was looking like this - Focused

The code that fixed the issue is

 <div class="form-floating mb-3">
      @Html.EditorFor(model => model.Recipient, new { htmlAttributes = new { @class = "form-control", @onchange = "javascript: Changed( this, 'recipient-name' );", @placeholder = "Recipient Name" } })
      @Html.ValidationMessageFor(model => model.Recipient, "", new { @class = "text-danger" })
      @Html.LabelFor(model => model.Recipient)
 </div>
0
Qing Guo On

Do you want something like below?

            <div class="form-floating">               
                <input asp-for="Recipient"  class="form-control"  />
                <label asp-for="Recipient"></label>
                <span asp-validation-for="Recipient" class="text-danger"></span>
            </div>