向视图公开缓存对象的最佳方法 [英] Best way to expose cached objects to the views
问题描述
我正在使用Translator对象(自定义类)公开网站文本(该对象存储数据库中的文本)。 Translator对象存储在缓存中,位于Application_Start()函数中。
I am using an Translator object (custom class) to expose website texts (the object stores texts from the database). The Translator object is stored in the cache, in the Application_Start() function.
我当前对Translator对象的使用是:
My current use of the Translator object is:
-
我有一个MasterViewModel
I have a MasterViewModel
public class MasterViewModel
{
public Translator Translator = HttpContext.Current.Cache.Get("Translator") as Translator;
}
每个视图都有一个视图模型,该视图模型是MasterViewModel固有的
Every view has a viewmodel, that inherents from MasterViewModel
public class RandomViewModel : MasterViewModel
{
}
在我看来,我可以使用我的翻译器对象
In my views i can use my Translator object
@model ViewModels.RandomViewModel
@Model.Translator.GetText(label)
我认为这不是一个很好的方法。
在App_Code中创建一个剃刀助手是一个好主意,以便我认为我可以使用
I don't think this is a nice aproach. Is it a good idea to make a razor helper in App_Code, so that in my views i can use
@Translate.GetText("RANDOM_TEXT")
这将是Helper函数(在Translate.cshtml中)
This will be the Helper function (in Translate.cshtml)
@helper GetText(string label)
{
Translator Translator = @Cache.Get("Translator") as Translator;
@: Translator.GetTextByLabel(label);
}
所以我的问题是向所有人公开缓存对象的最佳方法是什么我的看法。
以上方法之一是好方法吗?还是我应该采用其他解决方案?
So my question is what is the best way of exposing a cached object to all my views. Is one of the above approaches good? Or should i go with another solution?
(我希望我的英语还可以,我是荷兰人)
(I hope my english is okay, i am dutch)
推荐答案
有多种方法可以实现,但我将通过从 WebViewPage
派生一个基类并强制继承所有剃刀视图
There are different ways you can achieve that but I'll create a base class by deriving from WebViewPage
and force all the razor views inherit from this class.
public abstract class MyWebViewPageBase<T>: WebViewPage<T>
{
private Translator _translator;
protected override void InitializePage()
{
_translator = Context.Cache.Get("Translator") as Translator;
}
public string Translate(string label)
{
if(_translator != null)
return _translator.GetText(label);
return "";
}
}
现在我可以继承 MyWebViewPage
通过几种方式在剃刀视图中:
Now I can inherit the MyWebViewPage
in razor views through couple of ways:
第一种方法是在每个视图中都必须使用 @
The first approach is from every view you have to use the @inherits
directive.
Ex。
// Index.cshtml
@inherits MyWebViewPageBase
@model ...
....
另一种方法是全局设置所有视图的基础页面,为此您必须修改中存在的web.config视图
文件夹。
The other approach is a global way of setting the base page for all the views and for that you have to modify the web.config that exists in the Views
folder.
您必须设置 pageBaseType
> pages 元素,
You have to set the pageBaseType
of pages
element as below,
<pages pageBaseType="MyWebViewPageBase">
现在从任何视图中,您都可以简单地调用以下翻译方法,
Now from any view you can simply call the translate method as below,
@Translate("RANDOM_TEXT")
希望这会有所帮助!
这篇关于向视图公开缓存对象的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!