Search code examples
asp.net-mvcclassasp.net-mvc-5architecturevisual-studio-2019

What is the proper location for code classes (POCO, Models, etc.) in MVC?


I'm getting started with MVC, and I'm following this sample.

In it, we find that the Blog type is contained in the Controller's class file, in the Mvc3ViewDemo.Controllers namespace. This is a bit of a no-no in design methodology, as each class should be kept in its own file. (At least that's my particular convention.)

But when we move it out to its own file—even using the same namespace—the Controller can no longer see it:

enter image description here

(In VB.NET, the top-level namespace Mvc3ViewDemo is specified at the project level.)

I tried putting the file in both App_Code and the project root:

Namespace Controllers
  Public Class Blog
    Public Property Name As String
    Public Property Url As String
  End Class
End Namespace

The view can see it:

@ModelType IEnumerable(Of Controllers.Blog)

@Code
  ViewData("Title") = "Blog"
End Code

<h2>BLOG</h2>

<ul>
  @For Each oBlog In Model
    @<li><a href="@oBlog.Url">@oBlog.Name</a></li>
  Next
</ul>

enter image description here

...but the Controller can't.

If we put it in the Models folder, neither the Controller nor the View can see it.

Horror of horrors! Is MVC going to force me to put all of my classes in the same files as my controllers? What do we do when we need a model that's used by two or more controllers?

--EDIT--

In addition, I'm unable to add an Imports (using) statement for the target namespace to the Controller class file:

Models.Blog Bad Imports statement Refactor suggestion


Solution

  • The problem was that the Blog class file's Build Action was set to Content. Apparently this is the default action for new code files created under App_Code, which is why I missed it. It was right under my nose the whole time.

    I set it to Compile and now everything works as expected.

    --EDIT--

    I've filed a bug report which may be reviewed here.