何时在MVC 4 Razor中使用@Model和Model [英] When to use @Model and Model In MVC 4 Razor
问题描述
在我的PartialView中使用VS 2013,C#,我有以下内容;
Using VS 2013, C#, in my PartialView I have the following;
@model MyProject.Models.MyObject
我可以通过以下方式访问模型属性:
I can access the model properties by;
@Model.MyProperty
或
Model.MyProperty
我注意到,如果我不使用@Model,则不会获得显示对象属性名称的IntelliSense.除此之外,它们的工作原理完全相同.
I noticed that if I don't use the @Model, I don't get the IntelliSense to show the object property names. Apart from that they both work exactly the same.
因此,什么时候应该使用@ Model.MyProperty,什么时候应该仅使用Model.MyProperty?
Therefore when should I use @Model.MyProperty and when should I use just Model.MyProperty?
推荐答案
"@"符号告诉Razor View Engine后面有一个内联表达式.但是引擎足够聪明,在某些情况下您不需要'@'符号.例如,在简单的代码块中,例如
The '@' sign tells the Razor View Engine that an inline expression follows. But the engine is smart enough that you don't need the '@' sign in some cases. For example in simple code blocks like
@{
int x = 123;
string y = Model.AStringProperty;
}
或者如果您以后使用多个Razor/C#语句:
or if your are using multiple Razor/C# statements after another:
@for (var i = 0; i < Model.List.Count(); i++) {
var image = Model.List[i];
<div class="item @(i == 0 ? "active" : "")">
(... other stuff ...)
</div>
}
有点奇怪的是,您没有获得IntelliSense-您应该获得IntelliSense.
What's a little bit strange is that you don't get IntelliSense - you should get one.
更多示例: http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx/
因此,(运行时)编译器会告诉您何时使用"@"符号.
So the (runtime)compiler will tell you when to use the '@' sign or not.
这篇关于何时在MVC 4 Razor中使用@Model和Model的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!