RenderPartial and ViewBag
Asked Answered
M

2

5

I'm trying to modify this code: http://www.codeproject.com/Articles/260470/PDF-reporting-using-ASP-NET-MVC3 To make it to get the ViewBag data for render the View in the PDF.

Basically, I need to pass to Html.RenderPartial with a new Context my ViewBag, the code now is:

Html.RenderPartial(viewName, model);

And I'm trying to change it to something like:

Html.RenderPartial(viewName, model, new ViewDataDictionary(ViewBag));

I don't get any error but the Dictionary keeps empty.

BR

Monosome answered 25/6, 2013 at 15:6 Comment(0)
N
15

Try passing in the ViewData property instead of the ViewBag.

Html.RenderPartial(viewName, model, new ViewDataDictionary(ViewData));

The ViewBag property is a dynamic object, so the ViewDataDictionary constructor you are calling is the one that takes a object. You're better off to use the one that takes an already populated ViewDataDictionary. The data in the ViewBag and ViewData are the same.

Nix answered 25/6, 2013 at 15:27 Comment(2)
I can make it works, but I found also that I was using a variable named "ViewBag" I think that cannot be a great idea, so I changed it for a better name and I make this change and now works great!, thank you!Monosome
+1.Thank ! Great. I know about ViewData, but never used it. Some time stuck to this problem and most of time use to create a new viewModel to get out of the problem.Throat
D
0

You can use:

@Html.Partial(viewName)

In partial viewbag from main view will be accessible.

Ok. If you need render html from partial view to pdf you can use this code:

@{
    var htmlString = Html.Partial(viewName);    
    var pdfData = PdfComposerClass.CreatePdfStaticMethod(htmlString);   
}
Deoxyribose answered 25/6, 2013 at 15:13 Comment(1)
Thank you, but is not what I need, this is a special case, in some cases I need to render a view to a PDF, the api to do that works but is not getting the ViewBag data, I localize that Its create a new context, the problem seems in the line i wrote above.Monosome

© 2022 - 2024 — McMap. All rights reserved.