Search code examples
javascriptc#asp.netbootstrap-4glyphicons

Dynamically create glyphicon stars in a div based on numerical value retrieved from a MSSQL database C#


I am retrieving a rating(can be more than 5) from the database and I want to create glyphicon stars based on the value that is received on page load. See below for code used to retrieve the value.

int rating_count = DBinteract.get_rating_count(ticket_id);

I have tried to loop through and add the glyphicons to a div, based on the value retrieved however only one star is being displayed when the page loads.

for (int i = 0; i < rating_count; i++)
  {
    this.rating_count.InnerHtml="<span class='glyphicon glyphicon-star'></span>";
  }

The div I am trying to add the stars to

  <td>
         <div id="rating_count" runat="server"></div>
  </td>

Solution

  • You will need to append the string one to each other to get more than one span in your generated html, otherwise you are assigning the same string multiple times to .InnerHtml. Even more, and f you don't already do this, take in mind that the .innerHtml needs to be initialized to the empty string first:

    this.rating_count.InnerHtml = "";
    
    for (int i = 0; i < rating_count; i++)
    {
        this.rating_count.InnerHtml += "<span class='glyphicon glyphicon-star'></span>";
        //               look here: ^^
    }
    

    However, if you have Javascript support, you could use String.repeat() for this task:

    int rating_count = DBinteract.get_rating_count(ticket_id);
    this.rating_count.InnerHtml = "<span class='glyphicon glyphicon-star'></span>".repeat(rating_count);