crauscher
crauscher

Reputation: 6618

ASP.NET MVC Razor set style attribute in foreach

I want to set the width of a div via the style Attribute (to use the div as a bootstrap progress bar. I want to do this in a foreach loop

 @foreach (var item in Items)
      {
        <tr>
          <td>@item.Name</td>
          <td>
            <div class="progress">
              <div class="progress-bar" role="progressbar" aria-valuenow="@item.PercentageCompleted" aria-valuemin="0" aria-valuemax="100" style="width: @item.PercentageCompleted;">

              </div>
            </div>
          </td>
        </tr>
      }  `

What happens is that the style attribute is empty. Is there a way to achieve this?

Upvotes: 1

Views: 3227

Answers (2)

crauscher
crauscher

Reputation: 6618

It seems to be a culture problem. Using a ',' as decimal seperator in the with does not work, using a '.' works.

Upvotes: 0

Geoff James
Geoff James

Reputation: 3180

It depends what value your PercentageCompleted property gives.

If it is just a double number representing % (e.g. 50.1), you will need to append the % symbol to the end of your @item.PercentageCompleted like this:

... style="width: @(item.PercentageCompleted)%;">

wrapping the Razor content in parentheses to avoid errors. This would give you style="width: 50.1%"

If you are wanting to set the value in pixels, you will need to do the same, but add px to the end of your Razor code:

... style="width: @(item.PercentageCompleted)px;">

Most CSS attributes do not accept vanilla numbers (with the exception of 0); it needs to have a type defined to quantify what measurements to use the value for e.g. px, %, em, vh etc.

View this link to see more information on CSS units. Very useful.

Upvotes: 1

Related Questions