ASP.NET MVC Razor set style attribute in foreach

我的梦境 提交于 2021-01-28 18:21:00

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/37001838/asp-net-mvc-razor-set-style-attribute-in-foreach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!