简体   繁体   中英

Render HTML to a String from MVC Controller

I read this very helpful post: how to render html to a string instead of to the screen in MVC3.

I've created a function that does just that in my controller. I would now like to be able to call this method from class in another project so that I can offer this function as a service. The code looks like this:

 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();
        }

I'd like to call this class directly and not via the IIS. But then the ControllerContext is null. Can I specify the View on disc somehow?

MVC中的大多数控件都有一个名为"ToHtmlString();"的属性"ToHtmlString();"

http://msdn.microsoft.com/en-us/library/system.web.mvc.viewengineresult(v=vs.108 )

You can create the ViewEngineResult by providing list of locations instead of calling FindPartialView

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM