4

In my razor views, I have:

<link rel="stylesheet" href="css/print-layout.css" media="print" type="text/css" />

Which correctly applies that stylesheet when printing the page.

However, in some cases I'm rendering the view to an HTML string using something like:

var razorViewEngine = new RazorViewEngine();
ViewEngineResult viewResult = razorViewEngine.FindView(context, viewName, "_Layout", false);
// ...
var writer = new System.IO.StringWriter();
var viewContext = new ViewContext(context, viewResult.View, viewData, tempData, writer);
viewResult.View.Render(viewContext, writer);
return writer.ToString();

When doing so, how can I specify the media type, so that the "print-layout.css" stylesheet listed above is applied?

DaveD
  • 2,196
  • 1
  • 23
  • 33

1 Answers1

1

The print stylesheet is applied by the viewing user agent (browser) when printing.

You can change media="print" to media="all" to have it apply to all media types.

Update:

Why don't you try setting the stylesheet you want applied at Render time?

Try the (RenderPartial) to pass some data through so that you can conditional use "print" or "all".

Update 2: The HTML output won't differ, only the CSS rules that are applied to the actual rendered page that is viewed by a human. Or are you looking to see what styles are applied to the final rendered page DOM instead of what the HTML looks like?

David d C e Freitas
  • 7,481
  • 4
  • 58
  • 67
  • 1
    Thanks, but this doesn't answer the question. I don't want the stylesheet applied to all media types, but I do want to be able to render the view in code as if it were going to be rendered for that media type. – DaveD Dec 11 '13 at 03:22
  • Why don't you set the stylesheet when you render it in code? Updated my answer above. See also http://stackoverflow.com/questions/7768827/rendering-partial-view-in-code-mvc-razor http://stackoverflow.com/questions/4607843/razor-if-else-conditional-operator-syntax http://stackoverflow.com/questions/6295659/passing-parameters-in-partial-views-mvc3-razor http://stackoverflow.com/questions/6549541/how-to-pass-parameters-to-a-partial-view-in-asp-net-mvc – David d C e Freitas Dec 11 '13 at 03:38
  • 1
    Think of this as a unit test. I don't want to touch the view page at all. I just want this one bit of code to say "Hey, page. You already know how to apply appropriate styles for yourself, so let's pretend I'm printing (or mobile, or a normal screen). Gimmie your HTML." – DaveD Dec 11 '13 at 13:25
  • 1
    Oh, in that case then, your HTML will be exactly the same in both places, it's the CSS that is applied that differs. i.e. you aren't the one viewing it, you are just looking at the html string which is independent of the media type. – David d C e Freitas Dec 11 '13 at 23:37
  • 2
    You're right, I've been thinking about this entirely wrong and expecting external styles to be applied to the HTML, which of course doesn't make sense. Thanks – DaveD Dec 12 '13 at 15:43