【问题标题】:Use external CSS in `cshtml` with RazorEngine使用 RazorEngine 在 `cshtml` 中使用外部 CSS
【发布时间】:2019-03-06 11:48:18
【问题描述】:

我想在我的 cshtml 文件中使用外部和内部 CSS。

我在这里使用RazorEngine 编译器。

如果我尝试在不添加外部 CSS 的情况下运行,它工作正常。但是当我尝试添加外部 CSS 时,它会抛出下面提到的错误:

RazorEngine.Templating.TemplateCompilationException: '错误同时 编译模板。请尝试以下方法来解决这种情况: * 如果问题是关于缺少/无效的引用或多个定义,请尝试加载 手动丢失的引用(在编译的应用程序域中!)或 通过提供您自己的 IReferenceResolver 实现来手动指定您的引用。 有关详细信息,请参阅https://antaris.github.io/RazorEngine/ReferenceResolver.html。 目前,所有参考资料都必须以文件形式提供! * 如果你得到'class'不包含'member'的定义: 尝试另一个模型类型(例如'null'使模型动态)。 注意:您不能使用 typeof(dynamic) 使模型动态化! 或者尝试使用静态而不是匿名/动态类型。有关错误的更多详细信息: - error: (17, 29) The name 'Url' does not exist in the current context 编译的临时文件可以在(请 删除文件夹): C:\Users\pratik.soni\AppData\Local\Temp\RazorEngine_d253hedw.3b5 我们尝试编译的模板是: ------------- 开始 ------------ @model DRC.DTO.EFiling.NewEFilingDeclarationModel;

CSHTML 文件如下:

@model DRC.DTO.EFiling.NewEFilingDeclarationModel;
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=\, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="@Url.Content("~/wwwroot/CSS/StyleSheet.css")" rel="stylesheet" />
</head>
<body class="bg-gray">
    <h2 class="h2">VAT e-Filing</h2>
    <div class="bg-white">
        <div class="">

。 . .

模板编译代码如下:

public string CompileTemplate(string templatePath, string name, object model)
        {
            string rootPath = _env.ContentRootPath;
            string fullPath = Path.Combine(rootPath, templatePath, name).ToString();
            string templateSource = File.ReadAllText(fullPath);

            string templateString;
            if (Engine.Razor.IsTemplateCached(name, model.GetType()))
            {
                templateString = Engine.Razor.Run(name, model.GetType(), model);
            }
            else
            {
                templateString = Engine.Razor.RunCompile(templateSource, name, model.GetType(), model); //**GETTING ERROR ON THIS LINE**
            }

            return templateString;
        }

样式表.css

body {
}

.h2 {
    color: blue;
    margin-left: 20px;
}

【问题讨论】:

    标签: css razor asp.net-core-2.0 razorengine


    【解决方案1】:

    UrlHelper 仅存在于请求的上下文中。您在请求管道之外呈现视图,因此未定义 Url。但是,无论如何,您实际上并不需要它。您应该能够将代码更改为:

    <link href="~/wwwroot/CSS/StyleSheet.css" rel="stylesheet" />
    

    【讨论】:

    • 是的,它正在解决问题。但不幸的是,它没有将外部 CSS 应用于 PDF。
    • 在生成 PDF 时,外部链接不会真正起作用。这在很大程度上取决于您使用的库,但通常会提供一种包含外部 CSS 的方法,而不是在文档本身中引用它。
    猜你喜欢
    • 2017-10-06
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-03
    相关资源
    最近更新 更多