2009-11-24 61 views
3

在mu MVC應用程序頁面我有一個產品頁面(Controller:ProductController,Action:Index),其中列出了來自數據庫的所有產品。現在我有一個「添加產品」鏈接,提供填寫產品詳細信息的表單。在提交從AddProduct行動被調用,其中調用了StoredProcedure(在我的模型類中建模)。在成功添加之後,我使用RedirectAction(「Index」)。現在,我的StoredProcedure向我返回一條消息,指示添加的結果。我希望此消息存儲在ViewData中並顯示在索引頁上。我怎樣才能做到這一點?任何幫助將非常感激。在MVC中跨操作共享Viewdata MVC

回答

8

使用TempData而不是ViewData

public ActionResult Index() 
{ 
    ViewData["message"] = TempData["message"]; 
    return View(); 
} 

public ActionResult AddProduct() 
{ 
    TempData["message"] = "product created"; 
    return RedirectToAction("Index"); 
} 

和索引視圖:

<% if (ViewData["message"] != null) { %> 
    <div><%= Html.Encode((string)ViewData["message"]) %></div> 
<% } %>