I like the idea of HTML helpers, which allows me not to write all the HTML for common elements, while still gives me full control, preserves model-view separation and can be strongly typed.
I'm wondering if it is possible to generate CSS stylesheets or style definitions the same way - using helpers in view markup? Ideally, I would like to have some of the CSS generated based on some object-oriented rules and definitions.
I can't find any solutions that will offer开发者_如何学C anything more than stylesheet compression and merging.
On easy way would be to use a custom view result:
public class CssViewResult : PartialViewResult
{
private readonly object _model;
public CssViewResult(object model)
{
_model = model;
}
public override void ExecuteResult(ControllerContext context)
{
this.ViewData.Model = _model;
base.ExecuteResult(context);
context.HttpContext.Response.ContentType = "text/css";
}
}
and then a simple controller action:
public ActionResult MyCss()
{
SomeModel model = ...
return new CssViewResult(model);
}
and in the corresponding MyCss.cshtml
view:
@model AppName.Models.SomeModel
.foo {
background-color: @Model.SomeColor;
}
and then:
<link href="@Url.Action("MyCss", "SomeController")" rel="stylesheet" type="text/css" />
What you're asking for isn't impossible, but the way things are configured by default it wouldn't be possible. The reason is that CSS files are not "interpreted" like views are. They are just passed through.
You could write some handlers that generate CSS for you, but it wouldn't be anything like an HTML helper.
You could, theoretically, write an Html helper that will insert CSS inline, but that's really defeating the purpose behind CSS, because now you need to include the same CSS in multiple files, making your views larger and using more bandwidth.
So basically, the answer is.. No, there is nothing out there like Html helpers for CSS. And the reason it most likely doesn't exist is that it's more of a pain in the rear than it's worth.
精彩评论