HerGiz
HerGiz

Reputation: 967

Common functions and helpers ASP.NET MVC

I don't get something, and if somebody can clarify:

I need to access this function / helper from here and there:

namespace Laf.Helpers
{
    public class Common
    {
        public string TimeSpanToString(TimeSpan val)
        {
            return val.ToString(@"hh\:mm");
        }
    }
}

And in my controller I access it by:

var tmp = new Common();
string str = tmp.TimeSpanToString(tp.DepartureTime);
transferPoint.Add(
    new ListTransferPointVM { PortName = tp.PortName, DepartureTime = str }
str);

And the question is how can I achieve and not have duplicate in every controller:

DepartureTime = TimeSpanToString(tp.DepartureTime)

Possible Answer I just found a way that compiler is not frowning on:

public class TransferController : Controller
{
    private Common common = new Common();

    public ActionResult Index ()
    {
      ...

and later, when I need it:

string time = common.TimeSpanToString((TimeSpan)variable);

Upvotes: 0

Views: 2896

Answers (1)

Simon
Simon

Reputation: 1416

You could make your method string TimeSpanToString(TimeSpan) a static method. This way you can access it without having to make a Common object. Your code will look as follows:

namespace Laf.Helpers
{
    public class Common
    {
        public static string TimeSpanToString(TimeSpan val)
        {
            return val.ToString(@"hh\:mm");
        }
    }
}

And your Controller:

transferPoint.Add(
    new ListTransferPointVM { 
        PortName = tp.PortName, 
        DepartureTime = Common.TimeSpanToString(tp.DepartureTime) }
    Common.TimeSpanToString(tp.DepartureTime));

EDIT: As suggested by Michael Petrotta an extension method would be better. An implementation could be:

namespace LaF.ExtensionMethods
{
    public static class MyExtensions
    {
        public static string TimeSpanToString(this TimeSpan ts)
        {
            return ts.ToString(@"hh\:mm");
        }
    }
}

You can now call the method like:

tp.DepartureTime.TimeSpanToString();

More on Extension Methods in C#

Upvotes: 4

Related Questions