将 MVC 4 视图中的 html 转换为字符串 [英] Get html from MVC 4 view into a string

查看:31
本文介绍了将 MVC 4 视图中的 html 转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 这个问题.

这似乎正是我要找的东西,但我有一个问题.我不知道如何实际调用它.这是我目前所拥有的:

It seems that it will be exactly what i am looking for, but i have a problem. I don't know how to actually call it. This is what i have so far:

首先,我从我提到的解决方案中复制代码:

First i am copying the code from the solution i mentioned:

public string ToHtml(string viewToRender, ViewDataDictionary viewData, ControllerContext controllerContext)
{
    var result = ViewEngines.Engines.FindView(controllerContext, viewToRender, null);

    StringWriter output;
    using (output = new StringWriter())
    {
        var viewContext = new ViewContext(controllerContext, result.View, viewData, controllerContext.Controller.TempData, output);
        result.View.Render(viewContext, output);
        result.ViewEngine.ReleaseView(controllerContext, result.View);
    }

    return output.ToString();
}

这就是我所拥有的:

string viewToRender = "...";
int Data1 = ...;
int Data2 = ...;

System.Web.Mvc.ViewDataDictionary viewData = new System.Web.Mvc.ViewDataDictionary();
viewData.Add("Data1",Data1);
viewData.Add("Data2",Data2);

string html = ToHtml(viewToRender, viewData, ?????)//Here is my problem.

我应该在 controllerContext 参数中传递什么?

What should i pass in the controllerContext parameter?

推荐答案

您可以创建一个明显扩展控制器的基本控制器,并在基本控制器中使用上述功能,扩展此基本控制器的其他控制器将能够使用它.但是 ControllerContext 必须用作

You can create a base controller which obviously extends a controller and use above function in the base controller and other controller which extends this base controller will be able to use it. However the ControllerContext must be used as

Request.RequestContext

因此你的 BaseController 会像

And Hence your BaseController will be like

public class BaseController: Controller
{
//your function here
}

你的 ToHtml() 函数将是

And your ToHtml() function will be

protected virtual string ToHtml(string viewToRender, ViewDataDictionary viewData )
{
   var controllerContext=Request.RequestContext;
   var result = ViewEngines.Engines.FindView(controllerContext, viewToRender, null);

   StringWriter output;
   using (output = new StringWriter())
   {
      var viewContext = new ViewContext(controllerContext, result.View, viewData, controllerContext.Controller.TempData, output);
      result.View.Render(viewContext, output);
      result.ViewEngine.ReleaseView(controllerContext, result.View);
   }

   return output.ToString();
}

以及使用基本控制器

public class MyController: BaseController
{
//ToHtml(...);
}

这篇关于将 MVC 4 视图中的 html 转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆