【问题标题】:Sharing Viewdata across Actions in ASP.NET MVC在 ASP.NET MVC 中跨操作共享视图数据
【发布时间】:2009-11-24 11:04:11
【问题描述】:

在 mu MVC 应用程序页面中,我有一个产品页面(控制器:ProductController,操作:索引),其中列出了数据库中的所有产品。现在我有一个“添加产品”链接,它提供了一个表格来填写产品详细信息。在提交 from AddProduct 操作时,会调用一个 StoredProcedure(在我的模型类中建模)。成功添加时,我使用 RedirectAction("Index")。现在我的 StoredProcedure 返回一条消息,指示添加的结果。我希望将此消息存储在 ViewData 中并在索引页面上显示。我怎样才能做到这一点?任何帮助将不胜感激。

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    使用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>
    <% } %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-10
      • 2014-03-05
      • 1970-01-01
      • 2011-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多