I am trying to find a solution to build a CSS stri

2019-08-08 19:51发布

问题:

I am trying to find a solution to build a CSS string within my ASP.NET MVC Web Application. I would expect this to be at the selector level. So for example I may have a class "TableFormat" which might have the following CSS string.

font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
font-style: normal;
text-align: left;
background-color: green;
color: White;

Instead of having my users needing to know CSS, it would be far better to have a widget that allows them to select a font, color etc and then behind the scenes the widget would construct the above string. I then store this away into the DB for future use in a Razor View. I suspect it is the sort of thing that might exist as a JS widget. However I have not found anything apart from the dedicated CSS builders within bigger packages such as DW.

So my question is:

Do you know of a Javascript Control that does this, or another control perhaps within the ASP.NET MVC world that provides the above features. This would map to a textarea field. Otherwise I may need to write my own control.

回答1:

You need to build a backend part where the users would select the properties they want and store it in the database.

Than you can create a new Controller that would handle those custom values, something like this

public class CssController : Controller
{
    public ActionResult Custom()
    {
        ViewData["fontFamily"] = "Arial, Helvetica, sans-serif"; //get from database
        ViewData["fontSize"] = "12px";                           //get from database
        ViewData["selector"] = ".TableFormat";                   //get from database

        return View();
    }
}

Custom.cshtml View would look something like this

@{
     Layout = null;
     Response.ContentType = "text/css";
 }

@ViewData["selector"]
{
     font-family: @ViewData["fontFamily"];
     font-size: @ViewData["fontSize"];
}

If you navigate to /css/custom you would see something like this

.TableFormat
{
    font-family: Arial, Helvetica, sans-serif;
    font-size: 12px;
}

Now in the page that you want dynamically generated css you can include the view as a regular css file, for example:

 <link href="/Css/Custom" rel="stylesheet" />