Miguel Moura
Miguel Moura

Reputation: 39404

Render attribute content on condition

I need to conditionally define the content of an HTML 5 data attribute:

<img @(String.IsNullOrEmpty(prd.Reference) 
  ? String.Format("data-title='{0}'", prd.Name) 
  : String.Format("data-title='{0}({1})'", prd.Name, prd.Reference)) />

When I run this code it is rendered as follows (when reference is not null):

<img data-title="'Product"/>

Sometimes even more strange result ... The Reference is missing.

Does anyone knows what am I missing?

Upvotes: 0

Views: 45

Answers (1)

Mate
Mate

Reputation: 5274

Try with Html.Raw:

    <img @Html.Raw((String.IsNullOrEmpty(prd.Reference) 
  ? String.Format("data-title='{0}'", prd.Name) 
  : String.Format("data-title='{0}({1})'", prd.Name, prd.Reference)) />

Upvotes: 1

Related Questions