我不認爲使用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