我正在开发一个网格控件,我想在其中使用一些javascipt.我在类库项目中添加了一个js文件,并将其Buid Action设置为"Embded Resource".但是js/jquery函数(在js文件中实现)不能访问,我也无法在其他项目中查看包含的js文件,我正在使用那个dll,一切正常,期待这个.
请提供一些帮助.
你的动作方法Controller.使用反射,您可以读取resourceName并将其返回FileStreamResult.在视图中添加脚本路径为/Controller/Action/actualjsfile.js
测试样品的步骤如下
创建类库项目(JSDLL)
添加TestJS.js为嵌入资源(文件内容如下所示)
function MyAlert() {
alert("Hello! this is from the dll");
}
Run Code Online (Sandbox Code Playgroud)
在AssemblyInfo.cs中添加以下内容(需要添加对System.Web.dll的引用)
[assembly: System.Web.UI.WebResource("JSDLL.TestJS.js", "application/x-javascript")]
Run Code Online (Sandbox Code Playgroud)
编译类库项目并添加作为MVC项目的参考
在您的控制器中添加以下操作(与博客文章相同;但稍作修改)
public FileStreamResult ContentFile(string id)
{
string resourceName = Assembly.GetAssembly(typeof(JSDLL.Class1)).GetManifestResourceNames().ToList().FirstOrDefault(f => f.EndsWith(id));
return new FileStreamResult(Assembly.GetAssembly(typeof(JSDLL.Class1)).GetManifestResourceStream(resourceName), "text/javascript");
}
Run Code Online (Sandbox Code Playgroud)
简单视图进行测试(看一下如何.js引用文件.onClick我从.js文件中调用函数)
@{
ViewBag.Title = "About Us";
}
<h2>About</h2>
<p>
Put content here.
<button type="button" onclick="MyAlert()">Text</button>
</p>
<script type="text/javascript" src="/Home/ContentFile/TestJS.js"/>
Run Code Online (Sandbox Code Playgroud)
产量

编辑(马修的评论)
这里有几个屏幕截图





