When to use @Model and Model In MVC 4 Razor

2019-08-19 02:11发布

问题:

Using VS 2013, C#, in my PartialView I have the following;

@model MyProject.Models.MyObject

I can access the model properties by;

@Model.MyProperty

Or

Model.MyProperty

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.

Therefore when should I use @Model.MyProperty and when should I use just Model.MyProperty?

回答1:

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;
}

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>
 }

What's a little bit strange is that you don't get IntelliSense - you should get one.

Some more examples: 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.



回答2:

The @ at the beginning is marking the following text as a code element, not view markup. So:

<li>@Model.Name</li>

or

<li>
    @if(condition){
        Model.Name
    }
</li>


回答3:

Basically, the should never work both the same.

If you are in a text block, only @Model.MyProperty should work. Other text should be displayed. (The @ introduces a "mini code block") In a code block, Model.MyProperty works fine, but the @ should be a syntax error.



回答4:

The @ symbol is used by the Razor parser to indicate C# code and is used to indicate inline expressions, single statement blocks, and multi-statement block.

It also has the benefit of strong typing your reference to the model.

This is why you're able to create code blocks such as the following:

@{ 
  int x = 123; 
  string y = "because.";
}

If your reference to the model is wrapped in a code block like @{} then you do not need to prefix your model reference with the @ symbol.

With this in mind I would always try to use the @ prefix when possible.