Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34170

Adding created Models to views requires full namespace

I'm creating my first MVC application using MVC 6. While for example in Register.cshtml (which is created by default) the model is added like:

@model RegisterViewModel

But when I want to add Models that I created I have to do it like:

@model ProjectName.Models.HomeModels.MyModel

Note: I know how to import namespaces, what I want to know is that in the default views, there is no namespace import and adding models anyway, but for the models I created myself, they don't.

Upvotes: 0

Views: 1252

Answers (2)

Chris Pratt
Chris Pratt

Reputation: 239360

I think you're asking why you have to add usings for your classes, but other Microsoft classes and such are available in the view automatically without needing usings? There's a bit of black magic you're not seeing. The good news is that you can do the same thing. If you expand the Views directory in your project, you should see a Web.config file in there. This is different from the main Web.config used for your project; this one applies just to things in the Views directory. If you open this file, you'll see a section inside like:

<system.web.webPages.razor>
  <host factoryType="..." />
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
      <add namespace="System.Web.Mvc" />
      <add namespace="System.Web.Mvc.Ajax" />
      <add namespace="System.Web.Mvc.Html" />
      <add namespace="System.Web.Optimization"/>
      <add namespace="System.Web.Routing" />
      ...
    </namespaces>
  </pages>
</system.web.webPages.razor>

Behold: the missing usings. In case you haven't guessed, you can add your own namespaces here. Anything you add here will have the effect of automatically adding a using statement to your view for that namespace.

UPDATE

Whoops. Just noticed the core tag. I don't think this works anymore with core, but I'll leave my answer just in case someone needs the MVC method. In ASP.NET Core, you'll create a _ViewImports.cshtml file in your Views directory, instead, and add your using statements there:

_ViewImports.cshtml

@using MyProject.Models

Upvotes: 1

Kewin Rather
Kewin Rather

Reputation: 135

You need to use @using command to specify the namespace. When you did this that means that you are using this namespace on your view and you can access all the method from your view but be be careful about the duplicated names in other namespaces. Now you can add the model to your view. But the @using command only can be used for namespaces.

Upvotes: 0

Related Questions