在mvc 5中的主布局或页面中渲染页面脚本?

时间:2022-10-17 15:54:06

For the past, I have been rendering the script of the page at the bottom of the each page(cshtml file), but i feel that this is a bit hard to maintain. Basically, I have only one script for each page except for the master layout.

对于过去,我一直在每页底部(cshtml文件)渲染页面的脚本,但我觉得这有点难以维护。基本上,除了主布局之外,每个页面只有一个脚本。

Therefore, I would like to take alternative approach as follow, but I am not sure whether this is feasible or will have any other performance hit. Hope someone can clarify to me whether this is a good approach.

因此,我想采取以下替代方法,但我不确定这是否可行或是否会有任何其他性能影响。希望有人能向我澄清这是否是一个好方法。

<!-- In Master Layout.cshtml -->
@{
  string currentAction = ViewContext.RouteData.Values["action"].ToString();
  string currentScript = currentAction + ".js";
}

<script src= "@currentScript"></script>

1 个解决方案

#1


0  

In MVC you should use bundles and not call your scripts like you did, because it will improve your performance and make your scripts more compact when the site is published. You can read more here: http://www.asp.net/mvc/overview/performance/bundling-and-minification

在MVC中,你应该使用bundle而不是像你那样调用你的脚本,因为它会提高你的性能并使你的脚本在发布时更加紧凑。您可以在这里阅读更多内容:http://www.asp.net/mvc/overview/performance/bundling-and-minification

Also good article where to put your javascript files goes here and is explained really well: http://elegantcode.com/2010/03/30/your-javascript-goes-where/

也很好的文章把你的javascript文件放在这里,并解释得很好:http://elegantcode.com/2010/03/30/your-javascript-goes-where/

And as last to answer your question: you should minify the usage of code inside the views and this way you've build your path of the js file, if you change your project structure and move the js files into another location inside the project or change the routing your site would crash.

最后回答你的问题:你应该缩小视图中代码的使用量,这样你就可以构建你的js文件路径,如果你改变你的项目结构并将js文件移动到项目内的另一个位置或者更改您的网站崩溃的路由。

I hope this helps ;]

我希望这有帮助 ;]

#1


0  

In MVC you should use bundles and not call your scripts like you did, because it will improve your performance and make your scripts more compact when the site is published. You can read more here: http://www.asp.net/mvc/overview/performance/bundling-and-minification

在MVC中,你应该使用bundle而不是像你那样调用你的脚本,因为它会提高你的性能并使你的脚本在发布时更加紧凑。您可以在这里阅读更多内容:http://www.asp.net/mvc/overview/performance/bundling-and-minification

Also good article where to put your javascript files goes here and is explained really well: http://elegantcode.com/2010/03/30/your-javascript-goes-where/

也很好的文章把你的javascript文件放在这里,并解释得很好:http://elegantcode.com/2010/03/30/your-javascript-goes-where/

And as last to answer your question: you should minify the usage of code inside the views and this way you've build your path of the js file, if you change your project structure and move the js files into another location inside the project or change the routing your site would crash.

最后回答你的问题:你应该缩小视图中代码的使用量,这样你就可以构建你的js文件路径,如果你改变你的项目结构并将js文件移动到项目内的另一个位置或者更改您的网站崩溃的路由。

I hope this helps ;]

我希望这有帮助 ;]