Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return dynamic CSS with ASP.NET MVC?

Tags:

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 :)

like image 259
Morten Mertner Avatar asked Apr 26 '10 21:04

Morten Mertner


2 Answers

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"); }
like image 57
SLaks Avatar answered Sep 25 '22 23:09

SLaks


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");
like image 34
Jørn Schou-Rode Avatar answered Sep 21 '22 23:09

Jørn Schou-Rode