0

如果下面的 ASP.NET MVC2 代码在创建控制器响应中显示消息“测试”。

在 Mono 中,消息不会出现在 Create 视图中。

消息出现在创建后调用的下一个响应中。

如何使 Mono 像在 ASP.NET 中一样在同一请求中显示 TempData 值?

[HttpPost]
public RedirectToRouteResult Create()
{
 TempData["Message"] = "Test";
 return RedirectToAction("Index");
}


public ActionResult Index() {
  return View();
  }

Site.Master:

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>

<!DOCTYPE html>
<html>
<head runat="server">
    <script src="<%= Url.Content("~/Scripts/jquery/jquery-1.7.1.js")%>" type="text/javascript"></script>

 <% if (TempData["Message"]!=null) {
        %>
    $(function() {
        setTimeout( function() {
           showMessage ( '<%= TempData["Message"] as string %>');
           }, 300 );
      });
        <% } %>
    </script>
</head>
4

1 回答 1

1

我建议您TempData在控制器操作中而不是在视图中使用值:

[HttpPost]
public ActionResult Create()
{
    TempData["Message"] = "Test";
    return RedirectToAction("Index");
}

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

在视图内部:

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>

<!DOCTYPE html>
<html>
<head runat="server">
    <script src="<%= Url.Content("~/Scripts/jquery/jquery-1.7.1.js")%>" type="text/javascript"></script>

    <% if (ViewData["Message"] != null) { %>
        $(function() {
            window.setTimeout(function() {
                showMessage (<%= new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ViewData["Message"]) %>);
            }, 300);
        });
    <% } %>
    </script>
</head>

顺便说一句ViewData,我建议您使用视图模型,而不是使用 ,并将您的视图强类型化到此视图模型。

于 2012-10-16T16:46:46.483 回答