加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何渲染部分视图到字符串

发布时间:2020-12-15 18:53:30 所属栏目:asp.Net 来源:网络整理
导读:我有以下代码: public ActionResult SomeAction(){ return new JsonpResult { Data = new { Widget = "some partial html for the widget" } };} 我想修改它,以便我可以有 public ActionResult SomeAction(){ // will render HTML that I can pass to the
我有以下代码:
public ActionResult SomeAction()
{
    return new JsonpResult
    {
        Data = new { Widget = "some partial html for the widget" }
    };
}

我想修改它,以便我可以有

public ActionResult SomeAction()
{
    // will render HTML that I can pass to the JSONP result to return.
    var partial = RenderPartial(viewModel); 
    return new JsonpResult
    {
        Data = new { Widget = partial }
    };
}

这可能吗?有人能解释一下吗?

注意,我在发布解决方案之前编辑了问题。

解决方法

我选择了像ASP.NET MVC 4应用程序的扩展方法如下。我认为它比我看到的一些建议更简单:
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();

此外,此方法仍然保留视图的任何Model,ViewBag和其他视图数据。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读