我有一个方法可以将我的html转换为字符串以便导出为PDF 只有我需要将我的html(View)转换为字符串才能导出为PDF
代码:
public string RenderViewToString(Controller controller, string viewName, object viewData)
{
var renderedView = new StringBuilder();
using (var responseWriter = new StringWriter(renderedView))
{
var fakeResponse = new HttpResponse(responseWriter);
var fakeContext = new HttpContext(HttpContext.Current.Request, fakeResponse);
var fakeControllerContext = new ControllerContext(new HttpContextWrapper(fakeContext), controller.ControllerContext.RouteData, controller.ControllerContext.Controller);
var oldContext = HttpContext.Current;
HttpContext.Current = fakeContext;
using (var viewPage = new ViewPage())
{
var html = new HtmlHelper(CreateViewContext(responseWriter, fakeControllerContext), viewPage);
html.RenderPartial(viewName, viewData);
HttpContext.Current = oldContext;
}
}
return renderedView.ToString();
}
但是该值不会查看我的ViewBag:
ViewBag.Email = usuario.strUsuarioEmail;
ViewBag.Nome = usuario.strUsuarioNome;
代码导出PDF:
public ActionResult EventoVisualizarPDF()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["UrlAPI"]);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var id = Session["intCodigoGrupoUsuario"];
var intUsuarioId = Session["intUsuarioId"];
string url = "";
url = "api/usuario/GetBuscaUsuario/" + intUsuarioId;
HttpResponseMessage resposta = client.GetAsync(url).Result;
if (resposta.IsSuccessStatusCode)
{
var usuario = resposta.Content.ReadAsAsync<Usuario>().Result;
ViewBag.Email = usuario.strUsuarioEmail;
ViewBag.Nome = usuario.strUsuarioNome;
}
url = "api/evento/GetEventoByUsuario/" + id;
HttpResponseMessage response = client.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
var eventos = response.Content.ReadAsAsync<IEnumerable<Evento>>().Result;
return this.ViewPdf("Customer report", "RelatorioEventoPDF", eventos.OrderBy(m => m.strEventoCodigo));
}
else
{
string msg = response.IsSuccessStatusCode.ToString();
throw new Exception(msg);
}
}
如何在视图中从ViewBag中检索值?
答案 0 :(得分:1)
如果您熟悉blob storage in Azure,则可以将ViewBag
视为同一抽象类型的数据存储。
我假设你要输出这些值,以便它们可以被你的视图使用 - &gt; PDF转换方法,您在视图中所需要的只是:
<label id="vbEmail">@ViewBag.Email</label>
<label id="vbNome">@ViewBag.Nome</label>
这将输出您在控制器中设置的值为HTML。