在 cshtml razor 视图中分离 JavaScript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9682351/
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-10-26 07:26:07  来源:igfitidea点击:

Separating JavaScript in cshtml razor views

c#javascriptasp.netasp.net-mvc-3

提问by user1157885

I'm new to ASP.NET/MVC3 and I'm trying to figure out how to separate my JavaScript (which contains C#) from the rest of the HTML.

我是 ASP.NET/MVC3 的新手,我试图弄清楚如何将我的 JavaScript(包含 C#)与 HTML 的其余部分分开。

If I put them into .JS files and insert them with a script tag then the C# aspect of them stops working. What is the best way of separating your JavaScript code that also contains C# code in MVC 3 razor?

如果我将它们放入 .JS 文件并使用脚本标记插入它们,那么它们的 C# 方面将停止工作。在 MVC 3 razor 中分​​离还包含 C# 代码的 JavaScript 代码的最佳方法是什么?

Thanks.

谢谢。

回答by Zaid Masud

For many reasons, you're better off putting most, if not all of your JS into separate JS files (so that you can take advantage of reuse, minification, browser optimizations, content delivery networks etc.)

出于多种原因,最好将大部分(如果不是全部)JS 放入单独的 JS 文件中(以便您可以利用重用、缩小、浏览器优化、内容交付网络等)

To read the result of server-side razor code into your JS files use one of the following methods:

要将服务器端 razor 代码的结果读入您的 JS 文件,请使用以下方法之一:

1) Put your razor code into a javascript variable in the view(not tested code)

1) 将您的剃刀代码放入视图中的 javascript 变量中(未测试代码)

<script type="text/javascript">
  if(!MyGlobalVariables){
     MyGlobalVariables = {};
  }
  MyGlobalVariables.IndexUrl = "@Url.Action("Index")";
</script>

2) Use a custom attribute(preferrably prefixed with data- as suggested in HTML 5 spec). See related discussion here: Can I add custom attribute to HTML tag?

2) 使用自定义属性(最好以 data- 作为前缀,如HTML 5 规范中所建议)。请参阅此处的相关讨论:Can I add custom attribute to HTML tag?

<div data-index-url="@Url.Action("Index")"></div>

Then, use $(this).attr("data-index-url") in jQuery to access the rendered razor markup.

然后,在 jQuery 中使用 $(this).attr("data-index-url") 访问呈现的剃刀标记。

3) Put the C# into hidden input fieldson your view, and read the hidden input in your JS file.

3) 将 C# 放入视图中的隐藏输入字段,并读取 JS 文件中的隐藏输入。

<input id="indexUrl" type="hidden" value="@Url.Action("Index")" />

To read this in jQuery, you would use $("#indexUrl").val()

要在 jQuery 中阅读此内容,您可以使用 $("#indexUrl").val()

回答by Dave Bish

Instead, do something like this in your view page:

相反,在您的视图页面中执行以下操作:

var options = {
    parameter1 : '@(SomeC#Value)',
    parameter2 : '@(SomeC#Value)',
    parameter3 : '@(SomeC#Value)',
}

then call something like:

然后调用类似的东西:

myJavascriptObject.init(options);

and have the Javascript use the passed-in options to control flow, etc.

并让 Javascript 使用传入的选项来控制流程等。

回答by David Mulder

Javascript code should notcontain any dynamically generated code. If you need to load in certain config settings you should use a single inline script tag which defines the variables. Other options are loading in a json config file which is dynamically generated or basing it on dom content depending on the specific dynamic information you need. (Ajax being the most common way I would say, though that really would depend on your situation). Either way, the idea is that javascript and css files are alwaysstatic.

Javascript代码应该包含任何动态生成的代码。如果您需要加载某些配置设置,您应该使用一个定义变量的内联脚本标签。其他选项是加载到动态生成的 json 配置文件中,或者根据您需要的特定动态信息将其基于 dom 内容。(我会说 Ajax 是最常见的方式,尽管这实际上取决于您的情况)。无论哪种方式,这个想法都是 javascript 和 css 文件总是静态的。

回答by Kevin Boss

We convert our C# objects to Json with an extension on object and JavaScriptSerializer:

我们将 C# 对象转换为 Json,并在 object 和 JavaScriptSerializer 上进行扩展:

public static string ToJson(this object item)
    {
        return new JavaScriptSerializer().Serialize(item);
    }

Then we send set it on a variable (or in our case pass it to the constructor of the JavaScript Controller)

然后我们将它设置为一个变量(或者在我们的例子中将它传递给 JavaScript 控制器的构造函数)

回答by Abbas

If anything stops working while referencing to an external js-file, perhaps you're doing something wrong. Provide us with some example code on how you reference the external file. The other way is to just place the JavaScript-code between script-tags somewhere in the file. If it is in the _Layout.cshtml, you can place it in the head-tag and in another cshtml-file, place it on top between the script-tags.

如果在引用外部 js 文件时有任何内容停止工作,则可能是您做错了什么。向我们提供一些关于如何引用外部文件的示例代码。另一种方法是将 JavaScript 代码放在文件中某个地方的脚本标签之间。如果它在 _Layout.cshtml 中,你可以把它放在 head-tag 和另一个 cshtml 文件中,把它放在 script-tags 之间的顶部。

回答by Simon West

As others have said writing c# to your .js file probably isnt the best idea for various reason such as caching of dynamic variables. But sometimes we all have to do things we shouldnt. And if thats the case then there is a NuGet package that allows you to write Razor syntax inside a .js file its available here http://nuget.org/packages/RazorJS

正如其他人所说,由于各种原因,例如缓存动态变量,将 c# 写入您的 .js 文件可能不是最好的主意。但有时我们都不得不做我们不应该做的事情。如果是这种情况,那么有一个 NuGet 包,它允许您在 .js 文件中编写 Razor 语法,它可以在此处获得http://nuget.org/packages/RazorJS