简体   繁体   English

asp.net mvc-在操作之间重用控制器值

[英]asp.net mvc - reusing controller values among actions

i have a main Landing page (initial page) in which i need to make a service call. 我有一个主要的登陆页面(初始页面),需要在其中进行服务呼叫。 the values of that model will help me determine to show another page/action or not. 该模型的值将帮助我确定是否显示其他页面/操作。

lets pick a scenario, Review date if its in past, i will show a new page/action "ReviewData" that is in the same controller .cs class only. 让我们选择一个方案,如果它是过去的“审阅日期”,我将显示仅在同一控制器.cs类中的新页面/操作“ ReviewData”。 If that date is in future, I will show another page/action "Summary" which is also using the same .cs controller class. 如果该日期是将来的日期,我将显示另一个页面/操作“摘要”,它也使用相同的.cs控制器类。

Now, if i go to "ReviewData", i need the same service call data that i made above earlier. 现在,如果我转到“ ReviewData”,则需要与上述相同的服务调用数据。 I don't want to make this service call every now and then, as all these attempts its same value. 我不想时不时调用此服务,因为所有这些尝试都具有相同的值。 how do i avoid this and possibly can reuse the data/model values from the first service call? 我如何避免这种情况,并且可能可以从第一个服务调用中重用数据/模型值?

You need some caching stratergies here is simple cache helper class 您需要一些缓存策略,这里是简单的缓存助手类

using System.Runtime.Caching;  

public class cacheservice: ICacheservice
{
    public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class
    {
        T item = MemoryCache.Default.Get(cacheKey) as T;
        if (item == null)
        {
            item = getItemCallback();
            MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(10));
        }
        return item;
    }
}

interface ICacheService
{
    T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class;
}

Usage: 用法:

cacheservice.GetOrSet("CACHEKEY", (delegate method if cache is empty));

Cache provider will check if there's anything by the name of "CACHEKEY" in the cache, and if there's not, it will call a delegate method to fetch data and store it in cache. 高速缓存提供程序将检查高速缓存中是否有“ CACHEKEY”名称,如果没有,它将调用委托方法以获取数据并将其存储在高速缓存中。

Example: 例:

var Data=cacheService.GetOrSet("CACHEKEY", ()=>SomeRepository.GetData())

You can customize according to your needs as well 您也可以根据需要进行自定义

The answer of the question : - Can reuse the data/model values from the first service call? 问题的答案:-是否可以重用第一个服务调用中的数据/模型值? - Yes. -是的 You can achieve this using Tempdata: https://msdn.microsoft.com/en-us/library/system.web.mvc.tempdatadictionary.aspx 您可以使用Tempdata实现此目的: https ://msdn.microsoft.com/zh-cn/library/system.web.mvc.tempdatadictionary.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM