我想使用實體框架在MVC3中創建一個嚮導。它需要通過幾個步驟來保持對象的狀態(本例中爲一篇文章)。
我有我的控制器中的一個靜態變量實例化一個新的文章。在不同的動作中,我使用TryUpdateModel將表單映射到靜態變量。問題是,似乎TryUpdateModel()也會更新數據庫。我需要TryUpdateModel來執行自動映射,並更新靜態_article變量,但我不希望它保留到數據庫,直到最後一步!我知道在MVC中創建一個嚮導有很多可行的解決方案,但我想知道該怎麼做,所以請不要選擇MVC嚮導模式。使用靜態對象的asp.NET MVC3中的嚮導
謝謝。
namespace website.Controllers
{
public class ArticlesController : BaseController
{
// private static variable to hold the chosen article in the wizard
private static articles _article = new articles();
/// <summary>
/// Index page shows a list of articles in a webgrid
/// </summary>
/// <returns></returns>
public ActionResult Index()
{
List<articles> _articles = Data.getArticles();
return View(_articles);
}
/// <summary>
/// First page of the article wizard
/// </summary>
/// <returns></returns>
public ActionResult BasicDetails(string id, string nextButton)
{
// back or next doesn't matter - store form values
if (_article != null) TryUpdateModel(_article);
if (nextButton != null)
{
return RedirectToAction("ArticleGroup");
}
else
{
_article = Data.GetArticleById(id);
return View(_article);
}
}
/// <summary>
/// Second page of the article wizard
/// </summary>
/// <returns></returns>
public ActionResult ArticleGroup(string nextButton, string backButton)
{
TryUpdateModel(_article);
if (backButton != null)
return RedirectToAction("BasicDetails");
else if (nextButton != null)
{
return RedirectToAction("Price");
}
else
{
return View(_article);
}
}
/// <summary>
/// Third page of the article wizard
/// </summary>
/// <returns></returns>
public ActionResult Price(string nextButton, string backButton)
{
TryUpdateModel(_article);
if (backButton != null)
{
return RedirectToAction("ArticleGroup");
}
else if (nextButton != null)
return RedirectToAction("LinkedClubs");
else
{
return View(_article);
}
}
/// <summary>
/// Last page of the article wizard
/// </summary>
/// <returns></returns>
public ActionResult LinkedClubs(string backButton)
{
if (backButton != null)
return RedirectToAction("Price");
else
return View(_article);
}
}
}
'TryUpdateModel'不更新任何數據庫。這是一個MVC特定的方法。它甚至不知道您正在使用數據庫。它所做的是,它從請求參數綁定提供的模型並應用驗證邏輯。即使你目前的設計錯誤,你現在不想要其他選擇嗎?您直接在視圖中使用您的域模型,而不是使用視圖模型。很抱歉地說出來,但恐怕很崎嶇的路在你這樣的設計之前。還有一個靜態對象,用於在ASP.NET應用程序中保存用戶特定狀態!? WTF?如果兩個用戶同時填充該向導會怎麼樣? –
如果我理解正確,您正在使用靜態來保存數據。這在Web應用程序中非常錯誤,我不知道從哪裏開始。如果你有多個用戶(它是一個網站,所以你將有多個用戶),他們將最終共享靜態數據。他們會看到對方的變化,改寫對方的變化,腐蝕對方的變化。這將是一個巨大的混亂。 –
謝謝你們。我剛剛開始使用MVC,並且讓我瞭解控制器中的靜態私有變量是每會話容器。 當然,如果圖案被破壞,它會回到繪圖板。無論如何,再一次,謝謝你的擡頭。 –