首页 文章

返回部分文本

提问于
浏览
1

我的MVC应用程序的一部分包括一个wiki . 除了标准的wiki格式之外,还有许多用于将数据呈现到模板中的特殊标记 . 解析这些标记时,它从存储库中获取数据,实例化一个视图模型并将其呈现为部分,然后将该部分插入到替换原始标记的标记中 . 最终标记本身在具有相关UIHint的任何属性中呈现为DisplayFor的一部分 .

代码的相关部分是:

private static void MatchSpecial(WikiHelper wh)
    {
        wh.match = SpecialTagRegex.Match(wh.sb.ToString());
        while (wh.match.Success)
        {
            wh.sb.Remove(wh.match.Index, wh.match.Length);
            string[] args = wh.match.Groups[2].Value.Split('|');
            switch (wh.match.Groups[1].Value.ToUpperInvariant())
            {
                case "IMAGE":
                    string imageid;

                    imageid = args[0];
                    Image i = baserepo.imagerepo.GetImage(imageid);
                    ViewModels.ImageViewModel ivm = new ViewModels.ImageViewModel(i, args);
                    wh.sb.Insert(wh.match.Index, wh.Html.Partial("ImageViewModel",ivm));
                    break;
            }
            wh.match = SpecialTagRegex.Match(wh.sb.ToString(), ws.end);
        }
    }

WikiHelper 的相关成员是:

wh.sb - StringBuilder containing the markup
wh.html - the HtmlHelper from the main view
wh.match - holds the current regex matches

在MVC2中,这很好用 . 我现在正在升级到MVC3和Razor ViewEngine . 尽管事实上Html.Partial应该返回部分的MvcHtmlString,而是返回一个空字符串并将内容直接写入响应,其结果是所有类似模板化的元素出现在HTML文件的最顶部(甚至在我的布局文件中之前) .

1 回答

  • 1

    鉴于您所描述的症状,我怀疑您是直接写入自定义助手中某处的响应流 . 因此,只要您输出到响应,请确保替换:

    htmlHelper.ViewContext.HttpContext.Response.Write("some string");
    

    有:

    htmlHelper.ViewContext.Writer.Write("some string");
    

    直接写入响应流在WebForms视图引擎中工作,因为它是来自经典WebForms的遗留物,这就是事物本应该起作用的方式 . 在ASP.NET MVC中虽然这是不正确的 . 它工作但不正确 . 所有帮助者都应该写入 ViewContext.Writer . Razor将事物写入临时缓冲区,然后将其刷新到响应中 . 它使用由内向外渲染 .

相关问题