Where can I place custom classes in ASP.NET MVC?

I have some utility functions and a pagination function. I want to create classes called Utility and Pagination for these functions, respectively, so that I can use this class function in several controllers.

So where can I put this class in the folder structure and how can I access?

+49
asp.net-mvc
Jul 17 '12 at 4:20
source share
5 answers

You can create a new folder under Helpers under the root and physically save your classes. I would save my classes under a different Helpers namespace

 namespace MyProject.Helpers { public class CustomerHelper { //Do your class stuff here } } 

To activate this in my other classes (e.g. controllers), I can either use the full name

 var custHelper=new MyProject.Helpers.CustomerHelper(); 

OR

add an Import statement at the top so I can skip the full name

 //Other existing Import statements here using MyProject.Helpers; public class RackController : Controller { public ActionResult Index() { var custHelper=new CustomerHelper(); //do something with this return View(); } } 

If you think that your Helper method can be used in another project, you can consider it physically physical in a separate project (type class libraries). To use this in your project, add a link to this project and use it as what we did above (use either the full name or use the import statement)

+62
Jul 17 2018-12-12T00:
source share

You can place your helper classes anywhere you find logical and convenient.

Personally, I create the Helpers folder from the main project folder.

You can use them anywhere, either by fully defining the class name, or using the using statement.

In Razor mode you should use

 @using MyProject.Helpers 

In the controller or model you should use

 using MyProject.Helpers; 
+6
Jul 17 '12 at 4:24
source share

You can create a new project and then put the general classes in the project. If you want to use them, just add a link to the project.

+5
Jul 17 2018-12-12T00: 00Z
source share

Another approach might be to create a base controller class and add your common logic and output your controller from your base controller.

 public class MyBaseController:Controller { public void CommonFunction() { } } 

Use as ...

 public HomeController:MyBaseController { } 
+4
Jun 15 '16 at 8:14
source share

Also, be sure to set the Build Action of your class to Compile. In Visual Studio 2015, by default, each class created in App_Code (by right-clicking β†’ Add β†’ class) received β€œContent” as an assembly action.

0
Sep 22 '17 at 17:23
source share



All Articles