c# – MVC 6 Controller中的ControllerContext和ViewEngines属性在哪里?

前端之家收集整理的这篇文章主要介绍了c# – MVC 6 Controller中的ControllerContext和ViewEngines属性在哪里?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我创建了一个新的MVC6项目,并建立了一个新的网站.目标是获得一个视图的渲染结果.我发现以下代码,但是我无法找到它,因为我找不到ControllerContext和ViewEngines.

这是我要重写的代码

protected string RenderPartialViewToString(string viewName,object model)
    {
        if (string.IsNullOrEmpty(viewName))
            viewName = ControllerContext.RouteData.GetrequiredString("action");

        ViewData.Model = model;

        using (StringWriter sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,viewName);
            ViewContext viewContext = new ViewContext(ControllerContext,viewResult.View,ViewData,TempData,sw);
            viewResult.View.Render(viewContext,sw);

            return sw.GetStringBuilder().ToString();
        }
    }

解决方法

ControllerContext

首先我应该提到一个控制器不再是一个顶级的上下文,一个动作就是.所以你可以用ActionContext替代ControllerContext

ViewEngines

这是事情有点尴尬!我不完全确定如何获得视觉引擎,但新的DI框架已经添加了一个可以为您完成此工作的CompositeViewEngine的引用.例如:

var engine = Resolver.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;

所以把这一切放在一起,这应该适合你:

protected string RenderPartialViewToString(string viewName,object model)
{
    if (string.IsNullOrEmpty(viewName))
        viewName = ActionContext.ActionDescriptor.Name;

    ViewData.Model = model;

    using (StringWriter sw = new StringWriter())
    {
        var engine = Resolver.GetService(typeof(ICompositeViewEngine))
            as ICompositeViewEngine;
        ViewEngineResult viewResult = engine.FindPartialView(ActionContext,viewName);

        ViewContext viewContext = new ViewContext(
            ActionContext,sw,new HtmlHelperOptions() //Added this parameter in
        );

        //Everything is async now!
        var t = viewResult.View.RenderAsync(viewContext);
        t.Wait();

        return sw.GetStringBuilder().ToString();
    }
}
原文链接:https://www.f2er.com/csharp/96074.html

猜你在找的C#相关文章