2009-02-03 2 views

답변

3

당신은 다른 클래스에 TempDataDictionary을 통과해야합니다. 나는이 일을 꽤 많이하며, 다른 수업이 발표와 관련되어있는 한 오랫동안 잘못된 것은 없습니다.

0

이렇게하려면 현재 컨트롤러 컨텍스트가 필요합니다. 그렇지 않으면 불가능합니다.

ViewContext.Controller.TempData [ "어떤"] = 어떤

1

이 필요하지 않습니다. ControllerContext이 필요합니다. 현재는 HttpContext 만 필요합니다.

그리고 아무 것도 전달할 필요가 없습니다. SessionStateTempDataProvider을 새로 만들 수 있으며이 클래스의 SaveTempData- 메서드는 현재 세션의 특정 키에 IDictionary를 설정하기 때문에이 키를 사용할 수 있습니다.

(응용 프로그램이 사용자 정의 ITempDataProvider을 사용하지 않는 경우 당신이 할 경우, 당신은 분명 그 대신에 의존해야합니다.).

SessionStateTempDataProvider이 매우 간단한 클래스입니다 :

// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. 

using System.Collections.Generic; 
using System.Web.Mvc.Properties; 

namespace System.Web.Mvc 
{ 
    public class SessionStateTempDataProvider : ITempDataProvider 
    { 
     internal const string TempDataSessionStateKey = "__ControllerTempData"; 

     public virtual IDictionary<string, object> LoadTempData(ControllerContext controllerContext) 
     { 
      HttpSessionStateBase session = controllerContext.HttpContext.Session; 

      if (session != null) 
      { 
       Dictionary<string, object> tempDataDictionary = session[TempDataSessionStateKey] as Dictionary<string, object>; 

       if (tempDataDictionary != null) 
       { 
        // If we got it from Session, remove it so that no other request gets it 
        session.Remove(TempDataSessionStateKey); 
        return tempDataDictionary; 
       } 
      } 

      return new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); 
     } 

     public virtual void SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values) 
     { 
      if (controllerContext == null) 
      { 
       throw new ArgumentNullException("controllerContext"); 
      } 

      HttpSessionStateBase session = controllerContext.HttpContext.Session; 
      bool isDirty = (values != null && values.Count > 0); 

      if (session == null) 
      { 
       if (isDirty) 
       { 
        throw new InvalidOperationException(MvcResources.SessionStateTempDataProvider_SessionStateDisabled); 
       } 
      } 
      else 
      { 
       if (isDirty) 
       { 
        session[TempDataSessionStateKey] = values; 
       } 
       else 
       { 
        // Since the default implementation of Remove() (from SessionStateItemCollection) dirties the 
        // collection, we shouldn't call it unless we really do need to remove the existing key. 
        if (session[TempDataSessionStateKey] != null) 
        { 
         session.Remove(TempDataSessionStateKey); 
        } 
       } 
      } 
     } 
    } 
} 

따라서 우리는 다음을 할 수 있습니다 :

var httpContext = new HttpContextWrapper(HttpContext.Current); 
var newValues = new Dictionary<string, object> {{"myKey", myValue}}; 
new SessionStateTempDataProvider().SaveTempData(new ControllerContext { HttpContext = httpContext }, newValues); 

이것은 기존의 모든 t를 무시합니다. 즉, 순차적으로 데이터를 추가하려면 중간 컨테이너에 의존하거나 기존 값을 새 값과 병합하기위한 추가 로직을 작성해야합니다.

여기서는 내가 리디렉션하는 오류 페이지 처리를위한 것이지만 컨트롤러의 범위를 벗어나는 임시 데이터를 유지해야하는 논리가 있어야합니다.

+0

TempData에는 Session에서 지워지고 ControllerContext의 임시 컨테이너로 이동되는 것과 같은 MVC 프레임 워크에서 동작하는 기본 비헤이비어가 있습니다. TempData는 실제로 세션을 둘러싼 단순한 래퍼이므로 이처럼 데이터를 유지해야하는 경우 자체 세션 래퍼를 작성하는 것이 좋지만 TempData의 기존 동작에 대한 제약이없는 경우 이점이 있습니다. – Alex

1

ControllerBase.TempData 재산권

System.Web.Mvc.TempDataDictionary

당신은 공공 TempDataDictionary TempData을 사용할 수 있습니다

{얻을; 세트; }

TempData

예를 사용 TempData.Clear(); // 다른 클래스의 TempData를 지움

관련 문제