Dynamic Stylesheets Using Razor
You could create a custom view engine:
public class CSSViewEngine : RazorViewEngine
{
public CSSViewEngine()
{
ViewLocationFormats = new[]
{
"~/Views/{1}/{0}.cscss",
"~/Views/Shared/{0}.cscss"
};
FileExtensions = new[] { "cscss" };
}
protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
{
controllerContext.HttpContext.Response.ContentType = "text/css";
return base.CreateView(controllerContext, viewPath, masterPath);
}
}
and also register it with a custom extension in Application_Start
:
ViewEngines.Engines.Add(new CSSViewEngine());
RazorCodeLanguage.Languages.Add("cscss", new CSharpRazorCodeLanguage());
WebPageHttpHandler.RegisterExtension("cscss");
and inside web.config associate the extension with a build provider:
<compilation debug="true" targetFramework="4.0">
<assemblies>
...
</assemblies>
<buildProviders>
<add extension=".cscss" type="System.Web.WebPages.Razor.RazorBuildProvider, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</buildProviders>
</compilation>
[note, if you get an assembly binding error you might need to change the version number in the extension type to match your version of the Razor engine. You can check which version you are using by looking at the properties of your reference to the System.Web.WebPages.Razor assembly in your project]
And the last step is to have some controller:
public class StylesController : Controller
{
public ActionResult Foo()
{
var model = new MyViewModel
{
Date = DateTime.Now
};
return View(model);
}
}
and a corresponding view: (~/Views/Styles/Foo.cscss
):
@model AppName.Models.MyViewModel
/** This file was generated on @Model.Date **/
body {
background-color: Red;
}
which could now be included as a style in the Layout:
<link href="@Url.Action("Foo", "Styles")" rel="stylesheet" type="text/css" />
Dynamic colors css or inline styling asp.net mvc razor
The more maintainable way is to add a new column to your state look up table for the background color or css class. Seed the value with the color you want and read it from the table and use it.
Another option is to create CSS classes which matches with the state name/code/id. and use that. The problem with this approach is, every time you add a new status to the system, you need a code change as well (Adding a new css class). These css classes will be simply to override the bg color. So your code will generate the css class name by using the state code/name/id/.
Something like this.
@foreach (var item in Model)
{
<li class="li-@(item.State.Code)">
<!-- Existing code-->
</li>
}
Assuming you have State code values such as open and closed, you will create 2 css classes
.li-open
{
background-color:green;
}
.li-closed
{
background-color: red;
}
These specific css classes should override the default li styles. Use !important
as needed in your css
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, ...
ASP.Net MVC: How to use razor variable in CSS file
By default, MVC does not support writing server side codes in external CSS file and external Javascript files.
For your case to work, you can add an internal stylesheet in your view file itself, it will work.
Eg:
@{
ViewBag.Title = "Title";
}
<style>
.test {
background: url('@Model.LogoUrl') no-repeat scroll 0 0 transparent;
}
</style>
dynamically set css file name in _layout master page in Razor Mvc
@if(Request["size"] == 640) {
<link rel="stylesheet" type="text/css" href="//css/styles-640.css" />
} else {
<link rel="stylesheet" type="text/css" href="//css/styles-720.css" />
}
Dynamically generate styles inside code block (razor view)
You have to tell that from where plain text starts and form where razor code starts.
@:
tells that it is plain text not razor code and wrting @
or @(some code here)
telll that it is c# code block:
@foreach (var column in Model.Tabs[i].MegaMenuColumns)
{
if(column.Width || column.TextColor || column.BackgroundColor)
{
@:#column@(column.Id)
@:{
@:width: @(column.Width) ;
@:color: @(column.TextColor);
if(column.IsGradient)
{
@:background-image: -o-linear-gradient(bottom, @(column.BackgroundColor) 0%, @(column.BackgroundColorGradient) 100%);
@:background-image: -moz-linear-gradient(bottom, @(column.BackgroundColor) 0%, @(column.BackgroundColorGradient) 100%);
@:background-image: -webkit-linear-gradient(bottom, @(column.BackgroundColor) 0%, @(column.BackgroundColorGradient) 100%);
@:background-image: -ms-linear-gradient(bottom, @(column.BackgroundColor) 0%, @(column.BackgroundColorGradient) 100%);
@:background-image: linear-gradient(to bottom, @(column.BackgroundColor) 0%, @(column.BackgroundColorGradient) 100%);
}
else
{
@:background: @(column.BackgroundColor);
}
@:}
}
}
Add Dynamic CSS Class MVC Razor View
Try this :
$(document).ready(function () {
$('.widget:odd').addClass('widget-body-white');
$('.widget:odd').find('[class^=col-md]:first').attr('class','col-md-4 center');
$('.widget:odd').find('[class^=col-md]:last').attr('class','col-md-8 padding-none');
$('.widget:even').addClass('widget-body-gray');
$('.widget:odd').find('[class^=col-md]:last').attr('class','col-md-4 center');
$('.widget:odd').find('[class^=col-md]:first').attr('class','col-md-8 padding-none');
});
Demo
Related Topics
How to Colorize a White Png Image with CSS Only
CSS 62.5% Why Do Developers Use It
What Are Differences Between Rgb VS Rgba Other Than 'Opacity'
How to Hide Element Label by Element Id in CSS
The "Before" Pseudo Element Not Working in Font Awesome V.5
Bootstrap Modal Window Inside Another Div
Bottom of Custom Font Cut Off in Opera and Webkit
Why Do I Need an Empty 'Content' Property on an ::After Pseudo-Element
Cross Browser Text Gradient in Pure CSS Without Using Background Image
Resizing Background-Image Always Proportionally to Scale with a Center Point
Difference Between Width and Device-Width in CSS Media Queries
Open a File in Visual Studio's CSS Source Editor
CSS Change Custom Cursor Image Origin (Hotspot) to Center
Create Horizontally Scrolling List Item View Using Bootstrap Columns
Webkit Text Aliasing Gets Weird During CSS3 Animations