2013-04-11 75 views
0

我知道这有几种不同的方式,但我不确定我的具体问题已被问到。由于业务规则,我不能使用数据库在视图之间临时存储数据。静态变量已超出(多用户)。我试图避免会话和tempdata。如果我使用ViewState,我将存储大约9-12个模型的数据,这将减慢页面加载。如果用户返回表单,我需要重新填充多页表单。我知道这不是理想的方式,但任何人都可以建议一种方法来持久保存这些数据以用于会话变量以外的多个模型? Tempdata需要根据我的设想重新编写。我无法提供代码,我知道这不是一个有利的设计,但规则是有限制的。通过多个视图处理模型数据的最佳方法?

谢谢。

+3

你为什么要避免会话数据?这正是他们用于...... – 2013-04-11 16:39:34

+1

您的视图模型可以是页面的组合,因此每个页面将填充为用户从一个页面移动到另一个页面,因为您将传递整个模型到这些页面if用户返回一个页面,您将从您的模型中填充它。 – Flavia 2013-04-11 16:49:28

+2

我用@kadumel就可以了。我倾向于使用Singleton模式,在最终提交到数据库之前使用静态会话存储来编译向导的步骤。这是会话存储的目的。如果您绝对*无法*使用会话为我们未知的原因,您可以考虑使用HTML5存储瓦特/ JSON,但我不会推荐它,因为浏览器的限制和迄今为止实施的变化标准。 http://caniuse.com/#search=storage – 2013-04-11 17:04:28

回答

1

我不认为使用Session有什么问题,即使是MVC。这是一个工具,当你需要它的时候使用它。我发现大多数人倾向于避免Session,因为代码通常非常难看。我喜欢用一个通用的包装器对象,我需要在其中提供了一个强类型的和可重复使用的类(例如)会话存储:

public abstract class SessionBase<T> where T : new() 
{ 
    private static string Key 
    { 
     get { return typeof(SessionBase<T>).FullName; } 
    } 

    public static T Current 
    { 
     get 
     { 
      var instance = HttpContext.Current.Session[Key] as T; 

      // if you never want to return a null value 
      if (instance == null) 
      { 
       HttpContext.Current.Session[Key] = instance = new T(); 
      } 

      return instance; 
     } 
     set 
     { 
      HttpContext.Current.Session[Key] = value; 
     } 
    } 

    public static void Clear() 
    { 
     var instance = HttpContext.Current.Session[Key] as T; 
     if (instance != null) 
     { 
      HttpContext.Current.Session[Key] = null; 
     } 
    } 
} 

创建类需要被存储:

[Serializable] // The only requirement 
public class Person 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
} 

创建您的具体类型:(真的吗?真的很容易)

public class PersonSession : SessionBase<Person> { } 

使用它,只要你想,任何你想要的(只要它的序列化)

public ActionResult Test() 
{ 
    var Person = db.GetPerson(); 

    PersonSession.Current = Person; 

    this.View(); 
} 

[HttpPost] 
public ActionResult Test(Person) 
{ 
    if (Person.FirstName != PersonSession.Current.FirstName) 
    { 
    // etc, etc 

    PersonSession.Clear(); 
    } 
} 
相关问题