asp net mvc中的自定义扩展帮助器返回部分视图

时间:2015-12-03 11:52:35

标签: c# .net asp.net-mvc helpers

我想在helper中创建一个扩展方法,它接受单个参数partialViewName并将部分视图作为字符串返回。我发现ASP.NET MVC操作中使用的扩展名为

return PartialView("NameOfPartial").ReturnToString();

但我想让它像

string partialView = ViewExtensions.RenderToString("NameOfPartial");

原因是我的控制器必须是ApiController,而不是简单,所以它不使用System.Web.Mvc

这是我现在拥有的代码的一部分。

public static class ViewExtensions
{
    public static string RenderToString(string partialViewName)
    {
        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 = "Home"; // 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, partialViewName).View;

        var sb = new StringBuilder();

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

        return sb.ToString();
    }
}

也许有人知道如何让它更容易,更好,也更有效?

P.S此代码片段返回异常,并且我的部分视图位于Shared文件夹(基本ASP.NET MVC结构)中。

2 个答案:

答案 0 :(得分:1)

这是我们经常使用的实现。

protected string RenderPartialViewToString(string viewName, object model)
    {
        var view = viewName;
        if (string.IsNullOrEmpty(view))
        {
            view = ControllerContext.RouteData.GetRequiredString("action");
        }

        ViewData.Model = model;

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

            viewResult.View.Render(viewContext, sw);

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

答案 1 :(得分:-1)

请参阅以下实施:

ViewEngineResult viewEngResult = null;

viewEngResult = ViewEngines.Engines.FindPartialView(ControllerContext context,PartialViewPath);

var engineView = viewEngResult.View;