4

Can anyone explain to me what the following syntax mean?

ViewData ["greeting"] = (hour <12 ? "Godd morning" : "Good afternoon");

4 Answers 4

3

hour <12 ? "Godd morning" : "Good afternoon"

This ternary operator call (equivalent for if then else structure) will provide the string Godd morning if the value of hour is less than 12 and otherwise Good afternoon.

That result is put into ViewData["greeting"] which can later on be used in your view to display the message.

Sign up to request clarification or add additional context in comments.

Comments

1

You mean the operator on the right? It's Conditional Operator and it's like:

condition ? if_true : if_false

So in here if the hour is less than 12 then ViewData ["greeting"] will have string Godd morning assinged. Otherwise Good afternoon will be assigned.

You can read more about this operator here.

Hope this helps :)

Comments

1

This line passes data from the controller to the view template. The view template can use the content of ViewData["greeting"] for its processing. For example:

<p>
   <%: ViewData["greeting"] %>, earthling!
</p>

If the value of the variable hour is less than 12 the message will be "Godd morning, earthling", otherwise it will be "Good afternoon, earthling!".

Basically the boolean expression hour < 12 will be evaluated. If it is true the expression between the ? and the : will be assigned to ViewData["greeting"]. If it is false then the expression after the : will be assigned to the left side.

You can replace

ViewData ["greeting"] = (hour <12 ? "Godd morning" : "Good afternoon");

with this equivalent code:

if( hour < 12 )
   ViewData["greeting"] = "Godd morning";
else
   ViewData["greeting"] = "Good afternoon";

2 Comments

I think that he asked about syntax. Not about ViewData mechanism ;)
@Lukas: Thank you. I think it could be both, so I updated my answer.
1

Is the same thing as:

if (hour < 12)
   ViewData ["greeting"] = "Good morning";
else
   ViewData ["greeting"] = "Good afternoon";

Is just a ternary operator to simplify this common structure.

As ŁukaszW.pl said, just:

yourCondition ? isTrue : isFalse;

The ViewData is just a dictionary that the controller pass to the view.

The view is supposed to display data, then, you craete the "greeting" string on the controller and pass it to the view to display that information.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.