如何编写可在所有Razor视图中使用的函数?

时间:2015-01-03 12:38:31

标签: razor

我正在尝试编写一个可以从MVC 5和Razor中的数据库中获取语言资源的函数, 我希望它的使用非常简单,例如,下面的函数应该只是得到一些文本:

@T("ResourceType", "ResourceName")

我不想使用@this。 - 只是功能名称......

我看到一些关于它的帖子提到下面这一行,但仍然试图了解如何做到这一点

public abstract class WebViewPage<TModel> : System.Web.Mvc.WebViewPage<TModel>

任何帮助将不胜感激。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

我终于找到了一种方法,受到NopCommerce项目的启发,请参阅下面的代码。

代码可以在任何Razor(cshtml)视图中使用,如下所示:

<h1>@T("StringNameToGet")</h1>

另请注意,需要使用正确的新命名空间更新pageBaseType, 这是Views文件夹中的web.config - 不是主文件夹,应该如下所示:

  <system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="MyNameSpace.Web.Extensions.WebViewPage">
<namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization"/>
    <add namespace="System.Web.Routing" />
    <add namespace="APE.Web" />
  </namespaces>
</pages>

代码:

namespace MyNameSpace.Web.Extensions
{
public delegate LocalizedString Localizer(string text, params object[] args);

public abstract class WebViewPage : WebViewPage<dynamic>
{
}

/// <summary>
/// Update the pages element /views/web.config to reflect the 
/// pageBaseType="MyNameSpace.Web.Extensions.WebViewPage"
/// </summary>
/// <typeparam name="TModel"></typeparam>
public abstract class WebViewPage<TModel> : System.Web.Mvc.WebViewPage<TModel>
{
    private Localizer _localizer;

    /// <summary>
    /// Get a localized resources
    /// </summary>
    public Localizer T
    {
        get
        {
            if (_localizer == null)
            {
                //null localizer
                //_localizer = (format, args) => new LocalizedString((args == null || args.Length == 0) ? format : string.Format(format, args));

                //default localizer
                _localizer = (format, args) =>
                {
                    var resFormat = SampleGetResource(format);
                    if (string.IsNullOrEmpty(resFormat))
                    {
                        return new LocalizedString(format);
                    }
                    return
                        new LocalizedString((args == null || args.Length == 0)
                            ? resFormat
                            : string.Format(resFormat, args));
                };
            }
            return _localizer;
        }
    }

    public string SampleGetResource(string resourceKey)
    {
        const string resourceValue = "Get resource value based on resourceKey";

        return resourceValue;
    }
}

public class LocalizedString : System.MarshalByRefObject, System.Web.IHtmlString
{
    private readonly string _localized;
    private readonly string _scope;
    private readonly string _textHint;
    private readonly object[] _args;

    public LocalizedString(string localized)
    {
        _localized = localized;
    }

    public LocalizedString(string localized, string scope, string textHint, object[] args)
    {
        _localized = localized;
        _scope = scope;
        _textHint = textHint;
        _args = args;
    }

    public static LocalizedString TextOrDefault(string text, LocalizedString defaultValue)
    {
        if (string.IsNullOrEmpty(text))
            return defaultValue;

        return new LocalizedString(text);
    }

    public string Scope
    {
        get { return _scope; }
    }

    public string TextHint
    {
        get { return _textHint; }
    }

    public object[] Args
    {
        get { return _args; }
    }

    public string Text
    {
        get { return _localized; }
    }

    public override string ToString()
    {
        return _localized;
    }

    public string ToHtmlString()
    {
        return _localized;
    }

    public override int GetHashCode()
    {
        var hashCode = 0;
        if (_localized != null)
            hashCode ^= _localized.GetHashCode();
        return hashCode;
    }

    public override bool Equals(object obj)
    {
        if (obj == null || obj.GetType() != GetType())
            return false;

        var that = (LocalizedString)obj;
        return string.Equals(_localized, that._localized);
    }
}

}