user2094139
user2094139

Reputation: 327

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

Upvotes: 0

Views: 439

Answers (2)

Nate Anderson
Nate Anderson

Reputation: 690

value="@value"

This is setting the value of the option

@(Model.Amount == value ? "selected" : "")

This is shorthand boolean logic, or IF/THEN

The above is conceptually the same as this:

if (Model.Amount == value)
{
    return "selected";
}
else
{
    return "";
}

The View's model has a property on it named Amount, and this is a boolean used to determine if the option is the selected value in the select.

Upvotes: 1

StuartLC
StuartLC

Reputation: 107267

(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
{
  <%: "" %>
}

Upvotes: 2

Related Questions