Search code examples
c#asp.net-mvcglobal-variables

How to Create a Global Function then use on Controller


Im From VB.net base want to learn ASP.NET MVC

For Example : Function created below (how to create in global folder/cs and how to call it then use in Controller)

Function pRound(Number ,NumDigits) 
    Dim dblPower, vPSTEmp, intSgn

    dblPower = 10 ^ NumDigits
    vPSTEmp = CDbl(Number * dblPower + 0.5)
    pRound = Int(vPSTEmp) / dblPower
End Function

For vb I just add <--#include file="include/function.asp"-->

then can use it like pRound(number, 4)

Please Teach Me How to Do it. Thx a lot.


Solution

  • You could add a new class file in your solution and make a static class;

    namespace ProjectName.Functions
    {
       public static class Utility
       {
          public static float pRound(float number, int digits){
             float result = 0;
             // your code here
             return result;
          }
       }
    }
    

    Then in your controller, since a static class is instantiated at the start of the program, you could just call it;

    using ProjectName.Functions;
    
    public ActionResult TestController
    {
       // call Utility.pRound(), no need to instantiate the class
       float round = Utility.pRound(1,1);
    }