views:

230

answers:

3

I need a solution that lets me accomplish the following:

  • Returning CSS that is dynamically generated by an action method
  • Choosing CSS file depending on request parameter or cookie
  • Using a tool to combine and compress (minify) CSS

I am currently considering why there is no CssResult in ASP.NET MVC, and whether there might be a reason for its absence. Would creating a custom ActionResult not be the best way to go about this? Is there some other way that I've overlooked to do what I need?

Any other suggestions or hints that might be relevant before I embark on this task will also be appreciated :)

+4  A: 

You need to return a FileResult or ContentResult with a content type of text/css.

For example:

return Content(cssText, "text/css");
return File(cssStream, "text/css");

EDIT: You can make a Css helper method in your controller:

protected ContentResult Css(string cssText) { return Content(cssText, "text/css"); }
protected FileResult Css(Stream cssStream) { return File(cssStream, "text/css"); }
SLaks
A: 

I am currently considering why there is no CssResult in ASP.NET MVC, and whether there might be a reason for its absence.

Simply because the team had its hands full and obviously it's some effort to add ActionResults for all cases in life.

Would creating a custom ActionResult not be the best way to go about this?

It would be a correct way to do so. I added RssActionResult and AtomActionResult for my needs. It's also reasonable to add more types, for docs, pdfs, images etc.

Returning CSS that is dynamically generated by an action method

Also keep in mind that a browser would normally cache the css unless it sees some variation in the url. Adding an always incrementing parameter is a usual solution.

<link rel="stylesheet" href="http://site.com/styles.css?v=26"&gt;

An extra route parameter for version would probably work as well.

Developer Art
There is no point in creating a CssResult class.
SLaks
@SLaks: I like it more this way, so that I don't repeat content-type again and again or worse forget it once.
Developer Art
Then you can make a helper method. See my edit.
SLaks
+2  A: 

No need to create a custom ActionResult type. Since CSS a "just text", you should be fine using ContentResult. Assuming you inherited the Controller class, simply do:

return Content(cssData, "text/css");
Jørn Schou-Rode