I use this solution to add a tooltip to my webpage. The application is an MVC ASP.NET application with Razor pages. I want the text of the tooltip to have line breaks (<br/>
). This can be done by adding the HTML <br />
in the text. This works well, however, I have a function (see below) at the top of my page that renders a string that is added to my span-element with the <br>
-tags.
private static string GetEmployeeList(ProjectSchedule ps)
{
if (ps.Employees.Count > 0)
{
string empList = string.Empty;
foreach (var employee in ps.Employees)
{
empList += employee.Name + "<br/>";
}
return empList;
}
return string.Empty;
}
The result of the function is something like: "Name 1<br/>Name 2<br/>Name 3<br/>"
.
The piece of code rendering the tooltip looks like:
<div class="data-tooltip">
Developers
<span class="data-tooltiptext">@GetEmployeeList(item)</span>
</div>
The problem is that the <br/>
is not working, when the tooltips shows I see the hardcoded <br/>
as part of the string while I expected the result looks something like:
Name 1
Name 2
Name 3
The styling used:
.data-tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}
.data-tooltip .data-tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
position: absolute;
z-index: 1;
bottom: 100%;
left: 50%;
margin-left: -60px;
/* Fade in tooltip - takes 1 second to go from 0% to 100% opac: */
opacity: 0;
transition: opacity 1s;
}
.data-tooltip .data-tooltiptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: black transparent transparent transparent;
}
.data-tooltip:hover .data-tooltiptext {
visibility: visible;
opacity: 1;
}
Result:
Does someone have an idea how to solve this? TIA.
You have recognized the right problem in your answer, but that is not the correct solution. Your solution has the danger that if the names contain any HTML, that will be rendered as well, which opens you up to HTML and script injection attacks.
Generally you should avoid using @Html.Raw
and shouldn't generate HTML outside the template. All HTML generation should instead happen directly in the template:
<div class="data-tooltip">
Developers
<span class="data-tooltiptext">
@foreach (var employee in item.Employees)
{@employee.Name<br/>}
</span>
</div>