我试图使WriteSubstition在MVC 5中工作,并且在执行替换时,它是在请求的开始而不是在替换被调用的位置进行的。
我使用了以下扩展方法:
public static class HtmlExtensions
{
public delegate string CacheCallback(HttpContextBase context);
public static object Substitution(this HtmlHelper myHtml, CacheCallback cacheCallback)
{
myHtml.ViewContext.HttpContext.Response.WriteSubstitution(
c => HttpUtility.HtmlEncode(
cacheCallback(new HttpContextWrapper(c))
));
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
并在Index.cshtml中按如下所示调用它:
<div class="row">
<div class="col-md-4">
<h2Test</h2>
@DateTime.Now
@Html.Substitution(ctx => DateTime.Now.ToString())
@{Html.ViewContext.HttpContext.Response.WriteSubstitution(c => DateTime.Now.ToString());}
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
如您所见,我也尝试了不使用扩展方法的情况,即内联调用WriteSubstitution。页面呈现时,替换的块位于请求的开头:
10/10/2014 11:33:46 AM10/10/2014 11:33:46 AM<!DOCTYPE html>
<html>
Run Code Online (Sandbox Code Playgroud)
这是WriteSubstitution中的错误,还是我做错了什么?