ASP.NET MVC - 在母版页中引用样式表
我有一个位于 /Views/Shared 中的母版页。母版页引用 /Content
文件夹中的样式表。
如果我使用 "../../Content/style.css"
引用样式表,一切都会正常工作。但是,我的Web应用程序不在我们生产环境的根文件夹中,因此相对路径不起作用。
我尝试过“<%=ResolveUrl("~/content/style.css") %>"这在生产场景中确实有效,但随后 Visual Studio 中的设计器抱怨我的类是错误的(并且我无法在设计选项卡中预览带有 CSS 的页面)。
有没有一种解决方案可以在这两种情况下都起作用?我在 WebForms 中通过编写重置链接标记的服务器端代码来完成此操作。我可以在这里这样做,但我想避免这样做。
I have a master page that is in /Views/Shared. The master page references a stylesheet in the /Content
folder.
Everything works fine if I reference the stylesheet using "../../Content/style.css"
. However, my web application is not in the root folder in our production environment, so the relative path doesn't work.
I have tried "<%=ResolveUrl("~/content/style.css") %>" which does work in the production scenario, but then the designer in Visual Studio complains about my classes being wrong (and I cannot preview the page with CSS in the design tab).
Is there a solution that makes this work in both situations? I accomplished this in WebForms by writing server-side code that reset the link tag. I could do that here, but I would like to avoid it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试这种技术 - 以两种方式包含您的样式表。包含一个具有固定路径引用的引用,Visual Studio 将使用该引用来提供设计时支持,但将其包含在服务器端注释中,因此在运行时期间实际上不会包含它。第二个引用是运行时使用的“真实”引用,并且使用 Url.Content() 无论您的应用程序是否是子目录,它都可以工作。
Try this technique - include your stylesheet both ways. Include one with a fixed path reference that Visual Studio will use for design-time support, but enclose it in server-side comments so it's not actually included during run-time. The second reference is the "real" reference used at run-time, and with Url.Content() it'll work whether your app is a sub directory or not.
最佳实践是扩展 URL 帮助程序< /a>.这使您可以轻松地从您的视图中调用它,并且如果您的结构或文件发生变化,您不需要进行大量的查找/替换。
It is best practice to Extend the URL Helper. This allows you to easily call it from your view, and if your structure or files change, you don't need to do a massive find/replace.
在 Views 文件夹中,然后进入 Shared 文件夹有助于了解 MVC 中如何引用 CSS 文件。
In the Views folder and then going into the Shared folder helps understand how the CSS file is referenced in the MVC.