Home > Mobile >  Bootstrap 5 - Floating Labels with Razor syntax
Bootstrap 5 - Floating Labels with Razor syntax

Time:10-25

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 >
   @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

CodePudding user response:

Do you want something like below?

            <div >               
                <input asp-for="Recipient"    />
                <label asp-for="Recipient"></label>
                <span asp-validation-for="Recipient" ></span>
            </div>

CodePudding user response:

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 >
      @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>
  • Related