您是在 ASP.NET MVC 视图中编写 JavaScript 还是在单独的 JavaScript 文件中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4624626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:19:32  来源:igfitidea点击:

do you write your JavaScript in a ASP.NET MVC view ... or in a separate JavaScript file?

javascriptasp.net-mvc

提问by LeftyX

Trying to improve my coding styles I've tried different solutions but I can't figure out what is the best.
I've started putting JavaScript inside my views but I don't particularly like this solution.
It's hard to debug with Visual Studio, and it kinds of "pollutes" the page.
My new "trend" is to put the scripts for the page in a separate file.
The only problem I am facing is with the code.
To solve the problem I've defined JavaScript variables like this:

尝试改进我的编码风格我尝试了不同的解决方案,但我不知道什么是最好的。
我已经开始将 JavaScript 放入我的视图中,但我并不特别喜欢这个解决方案。
使用 Visual Studio 很难调试,而且它会“污染”页面。
我的新“趋势”是将页面的脚本放在一个单独的文件中。
我面临的唯一问题是代码。
为了解决这个问题,我定义了这样的 JavaScript 变量:

<script type="text/javascript">
    var PriceListFetchAction = '<%=Url.Action("Fetch", "PriceList")%>';
    var UploaderAction = '<%=Url.Action("UploadExcelPriceList", "PriceList")%>';
    var ModelId = '<%=Model.id%>';
    var ImportType = '<%=Model.Type%>';
    var customerCodeFetchAction = '<%=Url.Action("FetchByCustomerCode", "Customers")%>';
    var customerNameFetchAction = '<%=Url.Action("FetchByCustomerName", "Customers")%>';
    var ImportErpAction = '<%=Url.Action("ImportPriceListErp", "PriceList")%>';
    var imageCalendar = '<%=Url.Content("~/Content/Images/calendar.png")%>';
</script>  

and then I use the variables in my JavaScript file. What is the best in terms of performance, debugging, style for you?

然后我使用 JavaScript 文件中的变量。对您来说,在性能、调试和风格方面什么是最好的?

回答by Evan Nagle

I follow a handful of rules:

我遵循一些规则:

  1. Don't attach a variable directly to the DOM unless absolutely necessary.
  2. Place as much information in js files as possible. The fewer js files, the better.
  3. Version your js files. When publishing, minify and mash via Chirpy or SquishIt
  4. In js, minimize your dependency on dynamic server-side values (generated ids, etc.) when you can.
  1. 除非绝对必要,否则不要将变量直接附加到 DOM。
  2. 将尽可能多的信息放在 js 文件中。js 文件越少越好。
  3. 版本您的 js 文件。发布时,通过 Chirpy 或 SquishIt 缩小和混搭
  4. 在 js 中,尽可能减少对动态服务器端值(生成的 id 等)的依赖。

So, here's an example:

所以,这是一个例子:

I'll add jQuery and jQuery metadata to my project: http://plugins.jquery.com/project/metadata

我将向我的项目添加 jQuery 和 jQuery 元数据:http: //plugins.jquery.com/project/metadata

Then, in my master js file, I'll extend jQuery with my own namespace:

然后,在我的主 js 文件中,我将使用我自己的命名空间扩展 jQuery:

$.extend({
   fatDish : {
     url : {},
     urls : function(a) {
        $.extend($.fatDish.url, a);
     }
   }
});

Almost all of my customized js logic will live in the $.fatDishnamespace.

几乎所有我定制的 js 逻辑都将位于$.fatDish命名空间中。

Now, let's say I want to pass a MVC routeto $.fatDish. In my aspx page, I'd write the following:

现在,假设我想将MVC 路由传递给$.fatDish。在我的 aspx 页面中,我会写以下内容:

<script src="@Url.Content("~/path/master.js")" type="text/javascript"></script>
<script type="text/javascript">
   $.fatDish.urls({
      path1 : '@Url.Action("Index", "Home")'
   });
</script>

In a js file, I can now write:

在 js 文件中,我现在可以写:

window.location = $.fatDish.url.path1;

A second approach is to use jQuery metadata (which I mentioned above). On your aspx page, you could write something like:

第二种方法是使用 jQuery 元数据(我在上面提到过)。在您的 aspx 页面上,您可以编写如下内容:

<div class="faux-link {act:'@Url.Action("Index", "Home")'}">Go Somewhere</div>

Then, in your js file, you can grab the route value like so:

然后,在您的 js 文件中,您可以像这样获取路由值:

$('.faux-link').click(function() {
   var $this = $(this);
   var href = $this.metadata().act;
   window.location = href;
});

回答by jgauffin

I create separate javascripts for calculations / logic, but call them from my view. In this way I do not have to create global variables and its easier to re-use the javascripts.

我为计算/逻辑创建了单独的 javascripts,但从我的角度调用它们。通过这种方式,我不必创建全局变量,并且更容易重用 javascripts。

example javascript:

示例javascript:

function doSomeCoolProcessing(modelId, fetchAction)
{
    //some stuff
}

and in the view

并且在视图中

<script type="text/javascript">
    $('document').ready(function() {
        doSomeCoolProcessing('<%=Model.id%>', '<%=Url.Action("Fetch", "PriceList")%>');
    )};
</script>

It also makes it a lot clearer what's happening (and debugging when you return to your project after six months), since nothing happens unless you explicitly tell it to do so.

它还使正在发生的事情变得更加清晰(以及在六个月后返回项目时进行调试),因为除非您明确告诉它这样做,否则不会发生任何事情。

回答by Darin Dimitrov

Personally I always put javascript in separate files. Global variables which depend on routing or some server side information inside the view. Exactly as you do. As an alternative to storing global variables you could use anchor or form elements which already contain the url and then ajaxify them. As far as model values are concerned they could be stored also in DOM elements such as hidden fields, CSS classes, HTML5 data-* attributes, ... but this might not be applicable to all situations.

我个人总是将 javascript 放在单独的文件中。全局变量取决于视图中的路由或某些服务器端信息。和你一样。作为存储全局变量的替代方法,您可以使用已经包含 url 的锚点或表单元素,然后对它们进行 ajaxify。就模型值而言,它们也可以存储在 DOM 元素中,例如隐藏字段、CSS 类、HTML5 data-* 属性……但这可能并不适用于所有情况。

回答by jim tollan

vandalo,

破坏者,

I've borrowed a situation whereby the javascript is all in seperate file. however, using a custom action result on the controller, the js is invoked as an htmlhelper function and has a context with the page. the htmlhelper actually serves the code as a file and it's therefore cached, thus speeding up excecution/delivery.

我借用了一种情况,即 javascript 都在单独的文件中。但是,使用控制器上的自定义操作结果,js 将作为 htmlhelper 函数调用并具有页面的上下文。htmlhelper 实际上将代码作为文件提供,因此它会被缓存,从而加快执行/交付速度。

I know you'll be curious to see how this works, so will update the answer to show the mechanics of this a little later.

我知道你会很想知道它是如何工作的,所以稍后会更新答案以显示它的机制。

til then... (here's a link to where i got my inspiration. i then tweaked this to my own needs)

直到那时......(这是我获得灵感的链接。然后我根据自己的需要调整了这个)

ASP.NET MVC routing and paths is js files

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

ok, here's my worked example (a simple mvc 2 project that contains required helpers and classes) - enjoy:

好的,这是我的工作示例(一个简单的 mvc 2 项目,包含所需的助手和类) - 享受:

http://www.gatehousemusic.com/downloads/ServeJsExample.zip

http://www.gatehousemusic.com/downloads/ServeJsExample.zip

回答by Kaido

A separate file for tidiness at the least. The less languages you put into each file, the easier it will be to read what it does at a glance.

至少有一个单独的文件来保持整洁。您在每个文件中放入的语言越少,就越容易一目了然地阅读它的作用。

回答by Guillaume86

Here's my methods on ASP.NET MVC3 to complete the @weirdlover answer, one thing he's missing is the JSON encoding which is quite important when you want to safely inject data in js.

这是我在 ASP.NET MVC3 上完成@weirdlover 答案的方法,他缺少的一件事是 JSON 编码,当您想在 js 中安全地注入数据​​时,这非常重要。

If the data is not too big and can be logically attached to a DOM element, I use one (or several) data-attribute (don't require a jQuery plugin and leave the css class pretty) and a css class to find the elements from jQuery.

如果数据不是太大并且可以在逻辑上附加到 DOM 元素,我使用一个(或多个)数据属性(不需要 jQuery 插件并保持 css 类漂亮)和一个 css 类来查找元素来自 jQuery。

Stupid example:

愚蠢的例子:

HTML:

HTML:

<div class="text-widget" 
     data-options="@Json.Encode(new { url = Url.Action("Update", "Text", new { id = 3 }), uselessParam = true })">
  <input type="text" />
</div>

COFFEESCRIPT:

咖啡脚本:

class TextWidget
  constructor: (@element) ->
    @el = $ @element
    @options = @el.data 'options'
    @input = @el.find 'input'
    @input.change @update

  update: =>
     value = @input.val()
     $.post @options.url, 
       value: value
       , -> alert 'text saved'

$ ->
  new TextWidget element for element in $('.text-widget').get()

A little gotcha with Json.Encode and jQuery.data: if you use it on a simple string, you will get a quoted string in javascript: $().data('strattribute') == ' "hello" '. Just use Html.Encode in that case.

Json.Encode 和 jQuery.data 的一个小问题:如果你在一个简单的字符串上使用它,你将在 javascript 中得到一个带引号的字符串:$().data('strattribute') == ' "hello" '。在这种情况下只需使用 Html.Encode 。

Anyway I prefer to use a single attibute with an anonymous object I build in the controller, it's easier to maintain: data-options="@Json.Encode(Model.Options)".

无论如何,我更喜欢对我在控制器中构建的匿名对象使用单个属性,它更易于维护:data-options="@Json.Encode(Model.Options)".

If there is a lot of data, like a list of objects I will turn to ViewModels for knockoutjs, I use a <script>and var data = @(Html.Raw(Json.Encode(Model.MyData)));.

如果有很多数据,比如一个对象列表,我将转向 ViewModels forknockoutjs,我使用 a<script>var data = @(Html.Raw(Json.Encode(Model.MyData)));

I also use namespacing and closures to avoid poluting the global object.

我还使用命名空间和闭包来避免污染全局对象。