views:

51

answers:

4

Can anyone explain to me what the following syntax mean?

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

Thanks.

+1  A: 

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 :)

ŁukaszW.pl
+3  A: 

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.

XIII
+1  A: 

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";
John
I think that he asked about syntax. Not about ViewData mechanism ;)
ŁukaszW.pl
@Lukas: Thank you. I think it could be both, so I updated my answer.
John
+1  A: 

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.

Jesus Rodriguez