Are there any view helpers to generate CSS?

谁说胖子不能爱 提交于 2020-01-01 14:23:14

问题


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 anything more than stylesheet compression and merging.


回答1:


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.




回答2:


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" />


来源:https://stackoverflow.com/questions/5365488/are-there-any-view-helpers-to-generate-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!