Render razor view to string without munging the html

孤街醉人 提交于 2019-12-31 01:48:29

问题


I've previously found answers on how to render an MVC 4 view to a string. However, I started using Visual Studio 2013 and now the result is not as expected. See below.

 <$A$><$B$> <$C$> class="panel"<$D$>> <$E$> class="cover-wrapper"<$F$>> <$G$> href="     
 <$H$>/book/<$I$><$J$>1<$K$><$L$>/<$M$>"<$N$>><$O$> src="<$P$>http://www.
 example.com/images/image.jpg<$Q$>"<$R$> class="cover"<$S$> /> <$T$> href="<$U$>
 <$V$>"<$W$> target="_blank"<$X$> rel="nofollow"<$Y$> class="amazon-button"<$Z$>> <$a$> 
 class="amazon-cart"<$b$>> Link → 
 <$c$> class="content"<$d$>>..........

The code being used is this:

    public string RenderRazorViewToString(string viewName, object model)
    {
        ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
            var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
            return sw.GetStringBuilder().ToString();
        }
    }

Any idea as to why all the letters and dollar signs are showing up now or how I need to change my code to get it to give me usable html?


回答1:


This is actually a bug I ran into during the summer, see bug report and response from Microsoft here bug and workaround. Good news is that according to MS it should be fixed when VS2013 is released.

Workaround is to disable the browser link feature see here browser link feature



来源:https://stackoverflow.com/questions/18387499/render-razor-view-to-string-without-munging-the-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!