我不认为使用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();
}
}
你为什么要避免会话数据?这正是他们用于...... – 2013-04-11 16:39:34
您的视图模型可以是页面的组合,因此每个页面将填充为用户从一个页面移动到另一个页面,因为您将传递整个模型到这些页面if用户返回一个页面,您将从您的模型中填充它。 – Flavia 2013-04-11 16:49:28
我用@kadumel就可以了。我倾向于使用Singleton模式,在最终提交到数据库之前使用静态会话存储来编译向导的步骤。这是会话存储的目的。如果您绝对*无法*使用会话为我们未知的原因,您可以考虑使用HTML5存储瓦特/ JSON,但我不会推荐它,因为浏览器的限制和迄今为止实施的变化标准。 http://caniuse.com/#search=storage – 2013-04-11 17:04:28