ASP.NET MVC 路由和路径是 js 文件 [英] ASP.NET MVC routing and paths is js files

查看:17
本文介绍了ASP.NET MVC 路由和路径是 js 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们现在面临一个问题.我们有一个非常大的页面,里面有一个 loooong 内联脚本,它完成了所有的工作.我们现在想要混淆它并将其用作单独的 .js 文件.但问题是我们有由 Url 助手 (Url.Content()) 生成的路径.那么从页面中分离js文件而不使用硬编码路径字符串的最佳方法是什么?

we're facing a problem now. We have a pretty big page with a loooong inline script, which does all the work. We now want to obfuscate it and use it as a separate .js file. But the problem is that we have paths which are generated by Url helper (Url.Content()). So what is the best way to separate js file from the page and not using hard-coded path strings?

推荐答案

我通常在单独的视图中编写我的 javascript(只有 js 代码)并使用我自己的操作结果来呈现它.通过这种方式,我可以在服务器端利用 c#,如果需要,我可以使用模型,它将作为外部 js 文件包含在浏览器中(具有适当的缓存).我使用的操作结果可以在这里找到:http://codepaste.net/p2s3po

I usually write my javascript in separate views (with only js code) and use my own action result to render it. 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). The action result I use can be found here: http://codepaste.net/p2s3po

更新

你可以像这样从你的动作中使用动作结果:

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
                   };
}

然后你就当它是一个普通的视图(但只在视图中编写javascript).当然,您也可以采用任意数量的参数.

Then you just treat it as if it was a normal view (but only write javascript in the view). You can take any number of parameters as well of course.

你可以像这样包含它:

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

这篇关于ASP.NET MVC 路由和路径是 js 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆