Can Poyrazoğlu
Can Poyrazoğlu

Reputation: 34780

The name 'Model' does not exist in the current context in Razor

First, I've read all the questions regarding the issue.

Yes, I've checked/deleted my web.config file in the folder containing the view.

Yes, there are other other views in the same folder with no problems.

Yes, there are other classes in the same namespace with my model's namespace (but regardless of the class, I'm getting this error).

Yes, I've cleaned the solution.

Yes, I've restarted Visual Studio.

Yes, I'm on the latest version (as of writing, 2015, Update 2) of Visual Studio.

No, I'm not doing anything fancy about Razor pages, syntax, web.config etc.

No, I don't have any Visual Studio plugins.

Whatever I try, Visual Studio keeps telling me that the Model doesn't exist in the current context only for a particular file. There are other cshtml files just as this one in the same folder, many of them have strongly typed models (from the same folder, with the same protection level), and they are all working correctly. The problem exist just at the beginning of the file:

enter image description here

What is wrong?

Upvotes: 1

Views: 10263

Answers (3)

Guocahng
Guocahng

Reputation: 31

The solution from this article worked for me:

Run VS as administrator

Then run Uninstall-Package -Id Microsoft-Web-Helpers followed by: Install-Package -Id Microsoft.AspNet.WebHelpers

Upvotes: 2

dknaack
dknaack

Reputation: 60438

@model is a reserved word for specifying the type of the model.

Use @Model to get the instance.

In your case simply use another name for your variable.

Upvotes: 7

Can Poyrazoğlu
Can Poyrazoğlu

Reputation: 34780

While posting the question, I've figured out the error. It's due to Visual Studio's poor Razor syntax parsing.

As the Model may be null, I was assigning it to a new variable and if it was null, I was creating a new instance (I can't directly assign to Model as it's read-only), and the name of the variable was model:

var model = Model;
if(model == null) {
  model = ...
}

Anyway. I was using that model instance which was guaranteed to be non-null and have some values. Below, I was using <meta name="description" content="@model.Description" /> and Razor thought that I was declaring a new model type for the page when it saw @model, while the @ was for escaping into C# and model was my variable name. I've changed the varible model to m (or anything else that wouldn't be a keyword) and the problem went away.

Upvotes: 1

Related Questions