celsoap7 celsoap7 - 3 months ago 9
ASP.NET (C#) Question

Dynamic class for Html element breaking at space

On my ASP .Net project I have created the following function on a view (Razor):

@functions{

public string GetClassFromLevel_Global(decimal level)
{
return level >= Model.global_limit ? "progress-bar progress-bar-success" : "";
}
}


And then I use it like this:

<div class=@GetClassFromLevel_Global(total.Value) ...></div>


What I get in return:

<div class="progress-bar" progress-bar-success="" role="progressbar" aria-valuenow="1" aria-valuemin="0" aria-valuemax="100" style="width:100%"></div>


For some reason the returned string breaks at the space, how can I fix this?

Answer

Line breaks shouldn't be an issue in a well formed HTML. However, your Razor syntax is problematic:

<div class=@GetClassFromLevel_Global(total.Value) ...></div>

Will generate this html:

<div class=progress-bar progress-bar-success ...></div>

The first element progress-bar will be parsed as the value of the class attribute where as progress-bar-success will be parsed as an attribute with no value. I suspect the output you are giving in your questions is copied from a browser developpers tool HTML inspection. If you quote the function call, you will get the expected result:

<div class="@GetClassFromLevel_Global(total.Value)" ...></div>

Will generate:

<div class="progress-bar progress-bar-success" ...></div>