MVC 5中的全局功能 [英] Global functions in MVC 5

查看:60
本文介绍了MVC 5中的全局功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种定义全局函数的方法,以便可以在多个视图之间共享实现.

I am looking for a way where I can define global functions so I can share the implementation across multiple views.

我想知道我将它们放置在哪里?我尝试了_viewStart.cshtml和/Share/_Layout.cshtml,但似乎无法正常工作.

I was wondering where would I place them? I tried _viewStart.cshtml and /Share/_Layout.cshtml but It seems that is not working.

我不想为 HtmlHelper 类创建扩展.以我为例,扩展名将不起作用.我讨厌继续在多个视图中复制相同的功能.

I don't want to create an Extension to the HtmlHelper class. In my case, extensions won't work. I hate to keep copying the same function in multiple views.

@functions  {
  public static string GetColumnHeader(string columnName, string columnHeader, ISupportGridViewModel model)
  {
    return string.Format("{0} {1}", columnHeader, model.Sort == columnName ? model.SortDir == "ASC" ? "▲" : "▼" : string.Empty);
  }
}

对于那些评论我应该使用扩展名的人.这是我无法使其正常工作的示例.据我所知,Razor助手只是扩展方法,它是行不通的.

For those who commented that I should use extension. Here is the example where I am not able to to get it to work. As far as I know, Razor helpers are nothing more than extension methods and It won't work.

这是一个有效的例子

    var grid = new WebGrid(this.Model.Data);
    grid.Pager(WebGridPagerModes.Numeric);
    @grid.GetHtml(tableStyle: "table grid",
                  columns: grid.Columns(
                  grid.Column(columnName: "Time", format: (item) => MethodDefinedInView(item.EndTime))
  ))

这是一个不起作用的示例...

Here is an example that doesn't work...

var grid = new WebGrid(this.Model.Data);
grid.Pager(WebGridPagerModes.Numeric);
@grid.GetHtml(tableStyle: "table grid",
              columns: grid.Columns(
              grid.Column(columnName: "Time", format: (item) => Html.ExtensionMethod(item.EndTime))

))

推荐答案

只需在Utilities类中创建一个静态方法.您可以通过在Views文件夹内的Web.config中添加对名称空间的引用,或仅在每个cshtml文件的顶部来访问该视图.

Just create a static method in a Utilities class. You can access that in your view by either adding a reference to the namespace in the Web.config inside the Views folder, or just at the top of each cshtml file.

这篇关于MVC 5中的全局功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆