Search code examples
asp.net-mvcrazorternary-operatorstring-concatenation

.Net MVC Razor - Concatenating string inside ternary operator


How can I concatenate the following string to render correctly when used inside a ternary operator?

<input @(field.Type == "number" ? $"data-val-number=The field {field.Label}  must be a number" : "") />

The above doesn't render correctly - it outputs as follows missing the double quotes:

<input type="text" data-val-number=The field Time must be a number />

Solution

  • What about escaped quotes?

    <input @Html.Raw(field.Type == "number" ? $"data-val-number=\"The field {field.Label}  must be a number\"" : "") />