Dynamic CSS for ASP.NET MVC

Dynamic CSS for ASP.NET MVC?

I'd love to be able to run my CSS through Razor

What stops you?

public class CssViewResult : PartialViewResult
{
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.ContentType = "text/css";
base.ExecuteResult(context);
}
}

public class HomeController : Controller
{
public ActionResult Index()
{
return new CssViewResult();
}
}

and in ~/Views/Home/Index.cshtml:

@{
var color = "White";
if (DateTime.Now.Hour > 18 || DateTime.Now.Hour < 8)
{
color = "Black";
}
}
.foo {
color: @color;
}

Now all that's left is to include it:

<link href="@Url.Action("index")" rel="stylesheet" type="text/css" />

You can also make the template strongly typed to a view model, write loops, ifs, inclusions, ...

Best way to implement Dynamic CSS in .NET MVC

I would use the following way inside the layout page.
Perhaps I would/could improve the "GetThemeName" method so that it returns the full link string. So that the layout page only contains layout features instead of code.

ex:

@switch (UserSettings.GetThemeName())
{
case "Red":
<link rel="stylesheet" href="/Content/ThemeRed/css/default.css" />
break;
case "Blue":
<link rel="stylesheet" href="/Content/ThemeBlue/css/default.css" />
break;
default:
<link rel="stylesheet" href="/Content/Default/css/default.css" />
break;
}

the UserSettings.GetThemeName is a public static function which gets the users current "theme name" or "theme id"

How to return dynamic CSS with ASP.NET MVC?

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"); }

ASP.Net MVC 4 Load css File dynamically

You could have a query string parameter that sets whichStyleFlavor:

@{
string whichStyleFlavor = "1";
... some logic to check what they requested and change whichStyleFlavor
}

@Styles.Render("~/Content/style" + whichStyleFlavor + ".css")

Or you can do it on the client, by switching the CSS tag.

From here:

<link id="pagestyle" rel="stylesheet" type="text/css" href="default.css">
<script type="text/javascript">
function swapStyleSheet(sheet){
document.getElementById('pagestyle').setAttribute('href', sheet);
}

How to create Dynamic CSS blocks from Controller

I found that the issue: The code returned was inconsistent on what and how it was appended to the results and the view, at the mercy of the helper leveraged. Since it was inconsistent, different tags are emitted/appended (or not). It was left up to the developer to experiment and find out, and the documentation missing or the ASP team did not envision that use.

Either way - I got it to work, and I am sharing my class to help others.

public static class CssFromServer
{

//Handle both **Dynamic CSS** and Statics CSS files
internal static IHtmlString ServerCss(this HtmlHelper htmlHelper, bool loadFromfile, string pathToFile)
{
if(loadFromfile)
{
/**check valid path is invalid**/
if(String.IsNullOrEmpty(pathToFile)
return null;

// take a path that starts with "~" and map it to the filesystem.
var cssFilePath = HttpContext.Current.Server.MapPath(pathToFile.Trim());
// load the contents of that file
try
{
var cssText = File.ReadAllText(cssFilePath);
// I had to do this to get it working
return htmlHelper.Raw("<style>\n" + cssText + "\n</style>");
}
catch
{
// return nothing if we can't read the file for any reason
return null;
}
}
//not loading from file
return htmlHelper.Raw("<style>\n" + CreatMyServerCss(htmlHelper) + "\n</style>");
}

//my helper
internal static IHtmlString CreatMyServerCss(HtmlHelper htmlHelper)
{
// build your blocks here
return @"testcss { background-color: blak; } ";
}
}

Dynamically generated Javascript, CSS in ASP.NET MVC

The best solution so far I found for that is the following:

Dynamic Javascript and CSS in ASP.NET MVC using Razor Views

You just create views: CurrentUserOverrides.css.cshtml, ContactViewModel.js.cshtml. This views will contain single HTML block (<script> or <style>), so IntelliSense works fine. Then you create controller that renders that view, trims the root tag and return content with appropriate content type.



Related Topics



Leave a reply



Submit