简体   繁体   English

ASP.NET MVC路由和路径是js文件

[英]ASP.NET MVC routing and paths is js files

we're facing a problem now. 我们现在面临一个问题。 We have a pretty big page with a loooong inline script, which does all the work. 我们有一个非常大的页面,带有一个loooong内联脚本,可以完成所有工作。 We now want to obfuscate it and use it as a separate .js file. 我们现在想要对其进行模糊处理并将其用作单独的.js文件。 But the problem is that we have paths which are generated by Url helper (Url.Content()). 但问题是我们有由Url helper(Url.Content())生成的路径。 So what is the best way to separate js file from the page and not using hard-coded path strings? 那么将js文件与页面分开而不使用硬编码路径字符串的最佳方法是什么?

I usually write my javascript in separate views (with only js code) and use my own action result to render it. 我通常在单独的视图中编写我的javascript(只有js代码)并使用我自己的动作结果来渲染它。 This way I can take advantage of c# on the server side and I can use a model if needed and it will be included as a external js file in the browser (with appropriate caching). 这样我可以利用服务器端的c#,如果需要我可以使用模型,它将作为外部js文件包含在浏览器中(具有适当的缓存)。 The action result I use can be found here: http://codepaste.net/p2s3po 我使用的动作结果可以在这里找到: http//codepaste.net/p2s3po

Update 更新

You can use the action result like this from your action: 您可以在操作中使用此操作结果:

public ActionResult JsFile() {
    ViewData.Model = //Create model if you want one;
        return new JavascriptFileResult(true)
                   {
                       TempData = TempData,
                       ViewData = ViewData
                   };
}

Then you just treat it as if it was a normal view (but only write javascript in the view). 然后你只是将它视为普通视图(但只在视图中编写javascript)。 You can take any number of parameters as well of course. 当然,您也可以使用任意数量的参数。

You can include it like this: 你可以这样包括它:

<script type="text/javascript" src="<%=Url.Action("JsFile", "ControllerName")%>"></script>

You could create javascript functions to set the required paths and invoke them from a small script section from the page. 您可以创建javascript函数来设置所需的路径,并从页面的小脚本部分调用它们。

Javascript file: Javascript文件:

var resource1;
var resource2;

function setResourcesReferences(resource1, resource2, ...) {

}

ASPX file: ASPX文件:

<script type="text/javascript">
   setResourcesReferences(<% Url.Content("Resource1") %>, <% Url.Content("Resource2") %>, ...);
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM