声明和使用字符串时出错

Error when declaring and using a string

如何引用我在 MVC Razor View 中创建的变量?

我声明了一个变量如下:

@string bootstrapCSSPath = @Path.Combine(Model.pathToResourceDirectory, "bootstrap/css/bootstrap.min.css");

现在我想在html中使用这个变量。

这是我的代码:

<link href="@bootstrapCSSPath" rel="stylesheet" type="text/css" />

显示View时,出现如下错误:

Compiler Error Message: CS1525: Invalid expression term 'string'

在 Razor 中,您可以通过使用括号 {} 来声明变量或使用 C# 代码,在您的情况下:

@{
   string bootstrapCSSPath = @Path.Combine(Model.pathToResourceDirectory, "bootstrap/css/bootstrap.min.css");
}

<link href=@Html.Raw(bootstrapCSSPath) rel="stylesheet" type="text/css" />

您可以在 this 博客上查看更多信息

在视图中声明变量时,它应该包含在 {}

@{string bootstrapCSSPath = 
           @Path.Combine(Model.pathToResourceDirectory, 
               "bootstrap/css/bootstrap.min.css");
}

在你的问题中查看我的评论