Fix Razor CS0103: “The Name ‘model’ Does Not Exist in the Current Context” in ASP.NET MVC 5
Quick fix. First check the exact identifier in the compiler error. The lowercase Razor directive declares the view model. The uppercase Model property reads it. If the directive itself fails, check whether the deployed view inherits MVC’s Razor configuration.
This guide applies to ASP.NET MVC 5 on .NET Framework (System.Web.Mvc).
Separate a typo from a configuration problem
Use @model on its own directive line near the top of the file and use @Model in expressions. Writing @model.Name inside markup treats the declaration keyword as though it were a property. If the directive line itself is flagged across several files, investigate the effective Razor host and base type. If only Visual Studio shows an error while the running view works, check the IDE’s project context before changing the server.
Use a minimal typed view to isolate the issue
The sample assumes SampleSite.ViewModels.CustomerSummary is a public class with a Name property. Put the view under Views/Customers and have the corresponding action return that type. Build and open the page in the running application.
@model SampleSite.ViewModels.CustomerSummary
<h2>Customer summary</h2>
<p>@Model.Name</p>
Check Views/Web.config in the deployed tree
MVC 5 applications typically have a Razor Web.config under Views. Compare the deployed file with a known-good MVC 5 project targeting the same package versions. Check for the MVC Razor host and a page base type of System.Web.Mvc.WebViewPage under system.web.webPages.razor. A view inside an area may rely on an area-specific Views/Web.config. A shared view moved outside the configured folder can also lose the expected inheritance. Merge missing settings into the correct file rather than replacing the root application configuration.
Confirm the failure is gone
Test both a root view and the affected area view after publishing. If Razor now accepts the @model declaration but fails at runtime with a model-type mismatch, inspect the object passed to View(...). That runtime error means compilation has moved past the issue covered here.
Comments
Post a Comment