gpt4 book ai didi

asp.net-mvc - 是否可以使用 MVC 引用另一个程序集中的 javascript 和 css 文件?

转载 作者:行者123 更新时间:2023-12-02 18:12:08 24 4
gpt4 key购买 nike

我有一个 MVC 扩展 dll,我想将其添加到我的所有项目中。它包含我使用 MVC 引擎和 Twitter Bootstrap 创建的属性和一些自定义标签。基本上我想将我的扩展类所需的 js 和 css 版本存储在我添加到主 Web 项目的 dll 中。

是否可以在 Styles.Render/Scripts.Render 方法中或使用脚本或链接标记引用这些内容?

<link href="@Url.Content("somehowAccessADifferentDllHere")" rel="stylesheet" type="text/css" /> 
<script src="@Url.Content("somehowAccessADifferentDllHere")"></script>

最佳答案

当我开始使用 MVC 时,我想做同样的事情,但我发现这比应该做的要困难得多。反射似乎是目前实现此目的的唯一方法,下面的方法依赖于 .NET 框架一部分的内部方法。

经过一番研究,这是我最终得到的 HtmlHelper 扩展。

    // Cached delegate
private static Func<Assembly, string, bool, bool, ScriptManager, string> GetWebResourceUrlInternal = null;

/// <summary>
/// Returns a Url to a WebResource as a string
/// </summary>
/// <param name="type">Any type in the same assembly as the Resource</param>
/// <param name="resourcePath">The full resource Id in the specified assembly</param>
public static string GetWebResourceUrl(this HtmlHelper htmlHelper, Type type, string resourcePath) {

// find the internal method in AssemblyResourceLoader and cache the reflected result
if (GetWebResourceUrlInternal == null) {
MethodInfo mi = typeof(System.Web.Handlers.AssemblyResourceLoader).GetMethod(
"GetWebResourceUrlInternal", BindingFlags.Static | BindingFlags.NonPublic);

GetWebResourceUrlInternal = (Func<Assembly, string, bool, bool, ScriptManager, string>)Delegate.CreateDelegate(
typeof(Func<Assembly, string, bool, bool, ScriptManager, string>), mi, true);
}

return GetWebResourceUrlInternal(Assembly.GetAssembly(type), resourcePath, false, false, null);
}

在您的 View 中使用它

<link href="@Html.GetWebResourceUrl(typeof(YourLibClass), "styles.css")" rel="stylesheet" type="text/css" />

为了使其更加“友好”,我还重载了 GetWebResourceUrl,以便它只接受 resourcePath 参数并使用已知的 Type简化使用;

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

关于asp.net-mvc - 是否可以使用 MVC 引用另一个程序集中的 javascript 和 css 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22356525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com