Friday, May 8, 2015

Dynamic CSS with ASP.NET MVC and ContentResult

The ContentResult class is of type ActionResult, which means it is used to return text content from Controller Actions. There are multiple uses for the ContentResult, and one use is to create CSS dynamically. One would simply point a style sheet to an action and the action would return the dynamically generated CSS. In my case I am developing a Web app where each client can have their own theme, which is set in the database. I tackled this requirement with the following code:

    public ActionResult CssStyle()
    {
        string style = GetStyleFromDB(clientID);
        if (!String.IsNullOrWhiteSpace(style))
            return Content(style, "text/css");
        return View();
   }
 I would call this Action from the View like so:

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

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More