[英]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);
You could make your method string TimeSpanToString(TimeSpan)
a static
method. 您可以将方法
string TimeSpanToString(TimeSpan)
static
方法。 This way you can access it without having to make a Common
object. 这样,您无需创建
Common
对象就可以访问它。 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.