简体   繁体   中英

Adding classes to an ASP.NET MVC4 project

In an ASP.NET MVC4 project, I have a subdirectory called App_Code (manually created). It contains .cs files with classes in them. I use these classes in several different .cshtml files. The .cshtml files compile and work as expected.

My classes are in a namespace:

namespace Foo {
    public class Bar {
        //  ... properties
    }
}

I want to use one of these classes in a controller:

using System;
// ...
using Foo;

namespace MyProject.Controllers
{
    public class MyController {
        Foo.Bar SelectedBar { get; set; }
    }
}

When I do this, I get a compiler error:

Error   3   The type or namespace name 'Foo' could not be found (are you missing a using directive or an assembly reference?)

If I move the .cs files to the Controllers directory, then the .cshtml classes can't "see" them instead.

How do you add classes to a MVC4 project? Should I be creating a second project?

I've been doing C# for years now, but it's all been Windows Forms and XAML. With ASP.NET I'm on the learning curve like a rhino on skates.

I am assuming it is a model object and you can add them to the Model folder from within your project.

If you want to make your project more scalable you can create a separate c# library project and add a reference to your MVC app.

App_Code is used by plain old ASP.NET Web Forms Web Site project. When you place your classes there they're compiled by ASP.NET (not by Visual Studio like in MVC project). In a Web Site project you're basically exposing your code-files and the ASP.NET does the compilation for you. When using MVC you cannot create a Web Site project but instead you create a Project which is compiled before deployed.

If you want to use this directory in MVC project (not preferred) you can right click on files in App_Code and change Build Action from Content to Compile . (This way when you compile your MVC project the files from this directory will be taken and compiled into a .dll inside the bin directory).

Second and probably more preferred way is to organize your files differently. For example, in a typical project you might have such directories as /Infrastructure and /Models . You can add a separate Class Library project for you Business Logic Layer and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM