【问题标题】:MVC3 Razor - Response.WriteSubstitution always displays my text ontop of the pageMVC3 Razor - Response.Write Substitution 总是在页面顶部显示我的文本
【发布时间】:2012-06-28 16:49:34
【问题描述】:

。 亲爱的开发人员:)

我正在学习 ASP.NET MVC3,但在使用 Response.WriteSubsitution() 方法时遇到了困难。

每次我尝试在页面中使用它时,被替换的文本总是出现在页面顶部(screenshot here)。

考虑到我的控制器中有以下代码:

public class HomeController : Controller
{
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            return View();
        }

        [OutputCache(Duration=20)]
        public ActionResult About()
        {
            ViewBag.Date = DateTime.Now;
            return View();
        }
}

About.cshtml 中的代码:

@using MvcApplication1;
@{
    ViewBag.Title = "About Us";
}

<h2>About</h2>
<p>
    Date : @ViewBag.Date<br />
    Random Substitued number : @{ Response.WriteSubstitution(MvcApplication1.Helpers.Test); }
</p>

我的助手类:

namespace MvcApplication1
{
    public static class Helpers
    {
        public static string Test(HttpContext context)
        {
            Random r = new Random();
            return r.Next(0, 10).ToString(CultureInfo.InvariantCulture);
        }
    }
}

我错过了什么吗?

谢谢!

使用解决方案编辑:

我用@Darin Dimitrov 的解决方案解决了这个问题。

对于和我有同样情况的人,这是我的新代码。

我的控制器:

[DonutOutputCache(Duration = 10)]
        public ActionResult About()
        {
            ViewBag.Date = DateTime.Now;
            return View();
        }

        public string RandomNumber()
        {
            Random r = new Random();
            return r.Next(0, 10).ToString(CultureInfo.InvariantCulture);
        }

MvcDonutCaching 实现了我们必须使用的类 DonutOutputCacheAttribute,而不是内置的 OutputCacheOutput。

我的观点:

@using MvcApplication1;
@{
    ViewBag.Title = "About Us";
    Layout = "~/Views/Shared/Mobile/Layout.cshtml";
}

<h2>About</h2>
<p>
    Date : @ViewBag.Date<br />
    Random Substitued number : @Html.Action("RandomNumber", true)
    @Side
</p>

包重载Html.Action方法来控制缓存:)

感谢所有提供此主题的人。

【问题讨论】:

    标签: c# asp.net asp.net-mvc-3 razor


    【解决方案1】:

    我正在学习 ASP.NET MVC3,但当我使用 Response.WriteSubsitution() 方法时我被卡住了。

    忘记在 ASP.NET MVC 3 中使用 Phil Haack explains 的这个方法。根本不使用它。如果您想在 ASP.NET MVC 3 中实现甜甜圈缓存,该框架没有可以为您提供。

    如果您不想自己动手,有 third party packages 可以启用此功能。

    【讨论】:

    • 您好,感谢您的回答! MvcDonutCaching 包解决了我的问题。
    • "该框架没有可以为您提供。"这仍然适用于 MVC 5 吗?我应该停止用头撞墙来解决这个问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-09
    • 1970-01-01
    相关资源
    最近更新 更多