得到MVC 4查看HTML转换成字符串 [英] Get html from MVC 4 view into a string

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

问题描述

我试图使用从接受的答案<一个href=\"http://stackoverflow.com/questions/5266586/can-i-use-an-asp-net-mvc-razor-view-to-generate-an-nicely-formatted-html-body-as\">this问题。

I am trying to use the accepted answer from this question.

看来,这将是正是我期待的,但我有一个问题。我不知道如何实际调用它。这是我迄今为止:

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:

首先,我很抄袭我提到的解决方案code:

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天全站免登陆