简体   繁体   English

ASP.NET MVC中的语法ViewData

[英]Syntax ViewData in ASP.NET MVC

Can anyone explain to me what the following syntax mean? 任何人都可以向我解释以下语法是什么意思?

ViewData ["greeting"] = (hour <12 ? "Godd morning" : "Good afternoon"); ViewData [“greeting”] =(小时<12?“Godd morning”:“下午好”);

hour <12 ? 小时<12? "Godd morning" : "Good afternoon" “Godd morning”:“下午好”

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. 如果hour值小于12,那么这个三元运算符调用(相当于if then else结构)将提供字符串Godd早晨。

That result is put into ViewData["greeting"] which can later on be used in your view to display the message. 该结果将放入ViewData [“greeting”]中,以后可以在视图中使用它来显示消息。

You mean the operator on the right? 你的意思是右边的操作员? It's Conditional Operator and it's like: 它是Conditional Operator ,它就像:

condition ? if_true : if_false

So in here if the hour is less than 12 then ViewData ["greeting"] will have string Godd morning assinged. 所以在这里,如果hour小于12,那么ViewData ["greeting"]将有一个字符串Godd Godd morning Otherwise Good afternoon will be assigned. 否则将分配Good afternoon

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. 视图模板可以使用ViewData [“greeting”]的内容进行处理。 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!". 如果变量小时的值小于12,则消息将是“Godd morning,earthling”,否则它将是“下午好,地球!”。

Basically the boolean expression hour < 12 will be evaluated. 基本上将评估布尔表达式hour < 12 If it is true the expression between the ? 如果是true那么表达? and the : will be assigned to ViewData["greeting"] . 并且:将被分配给ViewData["greeting"] If it is false then the expression after the : will be assigned to the left side. 如果为false,则将:将指定给左侧的表达式。

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: 正如ŁukaszW.pl所说,只是:

yourCondition ? isTrue : isFalse;

The ViewData is just a dictionary that the controller pass to the view. ViewData只是控制器传递给视图的字典。

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. 该视图应该显示数据,然后,您在控制器上创建“问候”字符串并将其传递给视图以显示该信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM