Search code examples
razorcontent-management-systemc1-cms

Ternary function in Razor using Composite C1 keeps rewriting quotes as entities


I'm trying to do something pretty straight forward in a Composite C1 function but I believe the fact that Composite treats the function's HTML output as XML is causing issues. Unfortunately I cannot find a way around this one. So here's the offending line of code:

<input type="radio" name="@inputName" value="@radioLabel" required="@required" @(radioLabel.Trim() == inputValue.Trim() ? @"checked=""checked""" : "") />

The ternary function at the end is actually the problem. The output should end up being

checked = "checked"

but instead the quotes are turned into entities and it ends up being

checked=&quot;checked&quot; 

Here's a picture of the error enter image description here


Well, actually there is a simple way around this issue using the standard if/else logic below, but I would still like to know the answer to this question as I've had more than a few Composite C1-isms like this in the past and would like a solution.

@if(radioLabel.Trim() == inputValue.Trim())
{
  <input type="radio" name="@inputName" value="@radioLabel" required="@required" checked="checked" />
}
else
{
  <input type="radio" name="@inputName" value="@radioLabel" required="@required" />
}

Solution

  • You're doing it wrong and treat Razor like its nothing but a StringBuilder though its much smarter than that. Especially in this case, you should use Conditional Attributes

    The correct code is NOT to use Html.Raw, but to set your attribute-value to null if you don't want it to be rendered.

    @{
        string checked = radioLabel.Trim() == inputValue.Trim() ? "checked" : null;
    
       <input type="radio" name="@inputName" value="@radioLabel" required="@required" checked="@checked" />
    }