Search code examples
razorwhitespacehtml-encode

Encode WhiteSpace in Razor Dynamic Attributes


I have dynamic HTML attributes generated using Razor.

Everything seems to work fine except when I generate an attribute value with a whitespace within like:

item.Name = "Organisation Structure";

When I then try to render this value in a dynamic attribute, Razor thinks that the text after the whitespace is another entirely different attribute.

     <a href="@item.Url" @(!item.HasSubItems ? "data-tab-title=" + item.Name : "")></a>  

Which renders wrongly as:

<a href="/index" data-tab-title="Organisation" structure=""></a>

instead of like this:

<a href="/index" data-tab-title="Organisation structure"></a>

I have even tried to use Html.Encode(item.Name) like below:

<a href="@item.Url" @(!item.HasSubItems ? "data-tab-title=" + Html.Encode(item.Name) : "")></a>

Please, any solutions to this problem will be highly appreciated.


Solution

  • I solved the problem by simply doing a String.Replace("","&nbsp")

    <a @(!item.HasSubItems ? "data-tab-title=" + item.Name.Replace(" ","&nbsp") : "") href="@item.Url" ></a>  
    

    This solved the problem rather nicely.