获取Orchard CMS中Partial View的链接

时间:2013-06-28 07:50:27

标签: asp.net-mvc razor content-management-system orchardcms asp.net-mvc-partialview

我想在Orchard CMS中将RazorView渲染为字符串,但我不知道如何获取部分视图的链接以获取字符串。

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

如果在另一个MVC项目中 - 而不是Orchard - 它可以正常使用代码:

string result = RenderRazorViewToString("~/Views/Home/PartialViewEmail.cshtml", null);

但是在Orchard CMS中,它不知道从哪里获得部分视图。

我该怎么办?

非常感谢!

3 个答案:

答案 0 :(得分:5)

然而,更好的解决方案是采用Orchard的做事方式,使用形状。如果你这样做:

@Display.ViewEmail(SomeParameter: 42, SomeOtherParameter: "foo")

然后在名为/Views的{​​{1}}下的主题中创建一个文件,如果需要,可以引用作为ViewEmail.cshtml属性传入的参数。对Model的调用将导致呈现Display形状。

答案 1 :(得分:0)

我已经解决了这个问题。这很简单,如下面

PartialViewResult path = PartialView("PartialViewEmail");
string tmp = path.ViewName;
string result = RenderRazorViewToString(tmp, null);

答案 2 :(得分:0)

我选择了以下扩展方法:

public static class ViewExtensions
{
    public static string RenderToString(this PartialViewResult partialView)
    {
        var httpContext = HttpContext.Current;

        if (httpContext == null)
        {
            throw new NotSupportedException("An HTTP context is required to render the partial view to a string");
        }

        var controllerName = httpContext.Request.RequestContext.RouteData.Values["controller"].ToString();

        var controller = (ControllerBase)ControllerBuilder.Current.GetControllerFactory().CreateController(httpContext.Request.RequestContext, controllerName);

        var controllerContext = new ControllerContext(httpContext.Request.RequestContext, controller);

        var view = ViewEngines.Engines.FindPartialView(controllerContext, partialView.ViewName).View;

        var sb = new StringBuilder();

        using (var sw = new StringWriter(sb))
        {
            using (var tw = new HtmlTextWriter(sw))
            {
                view.Render(new ViewContext(controllerContext, view, partialView.ViewData, partialView.TempData, tw), tw);
            }
        }

        return sb.ToString();
    }
}

它允许我执行以下操作:

var html = PartialView("SomeView").RenderToString();

如果由于某种原因我仍想获得视图的完整路径,我可以执行以下操作:

var path = ((BuildManagerCompiledView)view).ViewPath; // Will be something like "~/Views/Shared/SomeView.cshtml"