Syntax ViewData in ASP.NET MVC
Can anyone explain to me what the following syntax mean?
ViewData ["greeting"] = (hour <12 ? "Godd morni开发者_JS百科ng" : "Good afternoon");
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.
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 :)
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";
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.
精彩评论