2015-08-06 4 views
1

Является ли это полезным? Вот моя ситуация, и вы могли бы предложить более простой или эффективный способ, если то, что я пытаюсь сделать, нецелесообразно. Здесь мы говорим о странице создания отчета. Во-первых, у меня есть хранимая процедура, которая занимает ДЕЙСТВИТЕЛЬНО долгое время, чтобы закончить выполнение, если не установлены фильтры/условия. Это означает, что это все, этот сохраненный proc возвращает список. Этот список затем заполняет таблицу в моем представлении. Это может быть от 10 до тысячи записей, но выполнение довольно длительное, потому что оно вычисляет это и то, что против тысяч записей, чтобы сделать его коротким, я не буду изменять свою хранимую процедуру.

Теперь с этого первого взгляда у меня есть кнопка для печати, которая вызывает другую страницу с тем же содержимым, но с удобной для печати страницей. Я не хочу выполнять мучительный хранимый процесс, чтобы получить тот же список, я хочу повторно использовать то, что уже создано. Как я могу это сделать?ASP.NET MVC Передача содержимого HTML-таблицы на другой вид

ответ

0

Насколько я понимаю, вы думаете о реализации какого-то способа кэширования данных, которые вы вычислили с помощью очень медленной хранимой процедуры?

Одним из вариантов было бы реализовать CacheManager и кэшировать результаты за определенный период времени:

/// <summary> 
/// Cache Manager Singleton 
/// </summary> 
public class CacheManager 
{ 
    /// <summary> 
    /// The instance 
    /// </summary> 
    private static MemoryCache instance = null; 

    /// <summary> 
    /// Gets the instance of memoryCache. 
    /// </summary> 
    /// <value>The instance of memoryCache.</value> 
    public static MemoryCache Instance 
    { 
     get 
     { 
      if (instance == null) 
      { 
       instance = new MemoryCache(); 
      } 

      return instance; 
     } 
    } 
} 

/// <summary> 
/// Cache Manager 
/// </summary> 
public class MemoryCache 
{ 
    /// <summary> 
    /// Gets the expiration date of the object 
    /// </summary> 
    /// <value>The no absolute expiration.</value> 
    public DateTime NoAbsoluteExpiration 
    { 
     get { return DateTime.MaxValue; } 
    } 

    /// <summary> 
    /// Retrieve the object in cache 
    /// If the object doesn't exist in cache or is obsolete, getItemCallback method is called to fill the object 
    /// </summary> 
    /// <typeparam name="T">Object Type to put or get in cache</typeparam> 
    /// <param name="httpContext">Http Context</param> 
    /// <param name="cacheId">Object identifier in cache - Must be unique</param> 
    /// <param name="getItemCallback">Callback method to fill the object</param> 
    /// <param name="slidingExpiration">Expiration date</param> 
    /// <returns>Object put in cache</returns> 
    public T Get<T>(string cacheId, Func<T> getItemCallback, TimeSpan? slidingExpiration = null) where T : class 
    { 
     T item = HttpRuntime.Cache.Get(cacheId) as T; 
     if (item == null) 
     { 
      item = getItemCallback(); 
      if (slidingExpiration == null) 
      { 
       slidingExpiration = TimeSpan.FromSeconds(30); 
      } 

      HttpRuntime.Cache.Insert(cacheId, item, null, this.NoAbsoluteExpiration, slidingExpiration.Value); 
     } 

     return item; 
    } 

    /// <summary> 
    /// Retrieve the object in cache 
    /// If the object doesn't exist in cache or is obsolete, null is returned 
    /// </summary> 
    /// <typeparam name="T">Object Type to put or get in cache</typeparam> 
    /// <param name="httpContext">Http Context</param> 
    /// <param name="cacheId">Object identifier in cache - Must be unique</param> 
    /// <returns>Object put in cache</returns> 
    public T Get<T>(string cacheId) where T : class 
    { 
     T item = HttpRuntime.Cache.Get(cacheId) as T; 
     if (item == null) 
     { 
      return null; 
     } 

     return item; 
    } 

    /// <summary> 
    /// Delete an object using his unique id 
    /// </summary> 
    /// <param name="httpContext">Http Context</param> 
    /// <param name="cacheId">Object identifier in cache</param> 
    /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns> 
    public bool Clear(string cacheId) 
    { 
     var item = HttpRuntime.Cache.Get(cacheId); 
     if (item != null) 
     { 
      HttpRuntime.Cache.Remove(cacheId); 
      return true; 
     } 

     return false; 
    } 

    /// <summary> 
    /// Delete all object in cache 
    /// </summary> 
    /// <param name="httpContext">Http Context</param> 
    public void ClearAll(string filter = null) 
    { 
     var item = HttpRuntime.Cache.GetEnumerator(); 
     while (item.MoveNext()) 
     { 
      DictionaryEntry entry = (DictionaryEntry)item.Current; 
      var key = entry.Key.ToString(); 

      if (filter != null && (key.ToLower().Contains(filter.ToLower()) || filter == "*")) //if filter, only delete if the key contains the filter value 
      { 
       HttpRuntime.Cache.Remove(entry.Key.ToString()); 
      } 
      else if (filter == null) //no filter, delete everything 
      { 
       HttpRuntime.Cache.Remove(entry.Key.ToString()); 
      } 
     } 
    } 
} 

Примечание: Я не пишу это сам, но не могу найти оригинал.

Это, как вы его используете:

// Retrieve object from cache if it exist, callback is performed to set and return object otherwise 
UserObject userObject = CacheManager.Instance.Get(httpContext, "singleId",()=> { 
    return new UserObject() { 
     Id = Guid.NewGuid() 
    }; 
}); 

// Retrieve object from cache if it exist, return null otherwise 
UserObject userObjectRetrieved = CacheManager.Instance.Retrieve<UserObject>(httpContext, "singleId"); 

// Remove object from cache 
CacheManager.Instance.Clear(httpContext, "singleId"); 

// Remove all object from cache 
CacheManager.Instance.ClearAll(httpContext); 
0

Не знаете, как ваш взгляд дизайн предназначается, чтобы быть, но вы можете заполнить версию для печати в то же время и скрыть его, пока кнопка не будет нажата.

Смежные вопросы