Reputation: 790
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.
Upvotes: 1
Views: 1318
Reputation: 790
I solved the problem by simply doing a String.Replace(""," ")
<a @(!item.HasSubItems ? "data-tab-title=" + item.Name.Replace(" "," ") : "") href="@item.Url" ></a>
This solved the problem rather nicely.
Upvotes: 3
Reputation: 5274
You could try :
@{
var dynamicLink = string.Format("<a href='{0}' {1}></a>", item.Url, (!item.HasSubItems)? "data-tab-title='" + item.Name +"'" : "");
}
@Html.Raw(dynamicLink)
Upvotes: 2