2009-11-24 60 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> 
<% } %>