Search code examples
asp.net-mvcrazorrazor-2

Can someone please explain this syntax in Razor to me?


Honestly I've looked for quite a while and I can't even find the general format for what I'm looking for, but I have the following Razor syntax that I do not have any idea on what it means.

<option value="@value" @(Model.Amount == value ? "selected" : "") >$@value</option>  

I'd like an explanation of that line of code if possible. In specific, why do I not have option value ="@Model.Amount" or something like that? I also dont understand how the Razor syntax works in terms of what comes after Model.Amount == value

What does the '?' indicate As well as the two values "selected" : "")

If someone could thoroughly explain this to me I would really appreciate it.

Thanks


Solution

  • (condition) ? (if true) : (else) is the C# conditional operator, not just for Razor.

    It writes out <option value="xxx" ... "selected"> if @value is equal to Model.Amount, i.e. selecting it in HTML.

    It is equivalent shorthand to

    if (Model.Amount == value)
    {
       <%: "Selected" %>
    }
    else
    {
      <%: "" %>
    }