我尝试使用MVC和iText从我的网页创建pdf,但是当我到达View时,ViewBag
数据为空。
在Controller中,ViewBag仍然有值。
为什么ViewBag数据为空?
从视图开始:
<td><span>
<a href='<%: Url.Action("HitlijstNaarPdf", new { AID_Hitlijst = ViewBag.Huidig })%>' target="_blank">
Download lijst
</a></span>
</td>
在控制器中调用结果
public FileStreamResult HitlijstNaarPdf(int? AID_Hitlijst = 0)
{
SelectPeriode(AID_Hitlijst);
GetHitlijstSettings();
var model = new HitlijstModel();
string sHtmlInhoud= this.RenderView("Index", model);
FileStreamResult result = PDFGenerator(sHtmlInhoud);
return result;
}
private void GetHitlijstSettings()
{
ViewBag.Datum = FHitlijstSettings.Datum;
ViewBag.Jaar = FHitlijstSettings.Jaar;
ViewBag.Week = FHitlijstSettings.Week;
}
在ControllerExtensions类中:
public static class ControllerExtensions
{
public static string RenderView(this Controller controller, string viewName, object model)
{
return RenderView(controller, viewName, new ViewDataDictionary(model));
}
public static string RenderView(this Controller controller, string viewName, ViewDataDictionary viewData)
{
var controllerContext = controller.ControllerContext;
var viewResult = ViewEngines.Engines.FindView(controllerContext, viewName, null);
StringWriter stringWriter;
using (stringWriter = new StringWriter())
{
var viewContext = new ViewContext(
controllerContext,
viewResult.View,
viewData,
controllerContext.Controller.TempData,
stringWriter);
// Here viewResult.ViewBag.Week still has data
// by debugging you see:
// viewResult.ViewBag.Week = 14;
// viewResult.ViewBag.Datum = "maandag 6 april 1987";
viewResult.View.Render(viewContext, stringWriter);
viewResult.ViewEngine.ReleaseView(controllerContext, viewResult.View);
}
return stringWriter.ToString();
}
}
当系统返回View(ViewBag.Week&lt; =&gt; null)时:
<th class="hitlijst_datum">Hitlijst - nummer <%: ViewBag.Week %> - <%: ViewBag.Datum %></th>
您收到以下消息:
以下方法或属性之间的调用不明确:&#39; System.IO.TextWriter.Write(string,params object [])&#39;和&#39; System.IO.TextWriter.Write(char [])&#39;
我试过:Html.Raw和ToString =&gt; Html.Raw (ViewBag.Week。 ToString())也是如此,但这也不起作用。我需要做些什么才能确保ViewBag在View中不为空?
答案 0 :(得分:2)
答案是:http://weblog.west-wind.com/posts/2012/May/30/Rendering-ASPNET-MVC-Views-to-String。我用此源替换ControllerExtensions。它有效。如果有人可以告诉我,为什么通过ControllerExtensions类的ViewBag消失了。高兴听到。