如何从Controller创建动态CSS块

时间:2017-01-23 01:31:21

标签: css asp.net asp.net-mvc razor

(已搜索 - 找到thisthisthis - 从文件返回CSS或使用第三方插件,我的需求更简单)。我希望从文件中提供Css

在ASP控制器中动态构建简单的CSS块 我想将其附加到页面末尾 &安培;防止缓存,因为它经常变化。

问题:为什么动态CSS阻止不在页面/ MVC视图调用中呈现不起作用,我可以做些什么来帮助调试呢?

在我的ASP MVC剃须刀active中:

button

我的自定义Css阻止disabled,即

View @Section

我的链接/内容类型是错误的,还是应该在头部样式部分?为什么它不呈现,我的内容类型或返回类型是错误的?

1 个答案:

答案 0 :(得分:0)

我发现了这个问题:返回的代码与在结果和视图中附加的内容和方式不一致,受到杠杆杠杆的支配。由于它不一致,因此发出/附加不同的标签(或不是)。开发人员需要进行实验并找出答案,和文档丢失,或者ASP团队没有设想使用。

无论哪种方式 - 我得到它的工作,我正在分享我的课程,以帮助他人。

public static class CssFromServer
{

  //Handle both **Dynamic CSS** and Statics CSS files
  internal static IHtmlString ServerCss(this HtmlHelper htmlHelper, bool loadFromfile, string pathToFile)
  {    
   if(loadFromfile)
   {
    /**check valid path is invalid**/
    if(String.IsNullOrEmpty(pathToFile)   
    return null; 

    // take a path that starts with "~" and map it to the filesystem.
    var cssFilePath = HttpContext.Current.Server.MapPath(pathToFile.Trim());
    // load the contents of that file
    try
    {
      var cssText = File.ReadAllText(cssFilePath);
      // I had to do this to get it working          
      return htmlHelper.Raw("<style>\n" + cssText + "\n</style>");
    }
    catch
    {
      // return nothing if we can't read the file for any reason
      return null;
    }
   }     
   //not loading from file
   return htmlHelper.Raw("<style>\n" + CreatMyServerCss(htmlHelper) + "\n</style>");
  }

  //my helper
  internal static IHtmlString CreatMyServerCss(HtmlHelper htmlHelper)
  {
   // build your blocks here 
   return @"testcss { background-color: blak; } ";
  }    
}