在CSHTML剃刀意见分离的JavaScript [英] Separating JavaScript in cshtml razor views

查看:108
本文介绍了在CSHTML剃刀意见分离的JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来ASP.NET/MVC3,我试图找出如何我的JavaScript(包含C#)从HTML的其余部分分开。

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.

如果我把它们放进.js文件和脚本标记然后将它们的C#方面停止工作插入。什么是分离你的JavaScript code的最佳方式,也包含在MVC 3剃须刀C#code?

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到单独的JS文件(,这样你可以重用的优势,缩小,浏览器的优化,内容分发网络等)

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.)

要读取服务器端剃须刀code的结果到您的JS文件使用下列方法之一:

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

1)把你的剃须刀code到JavaScript变量视图(未测试code)

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

2)在<建议使用自定义属性(preferrably $ P $与数据 - pfixed href=\"http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#embedding-custom-non-visible-data-with-the-data-attributes\"相对=nofollow> HTML 5规范)。在这里看到相关的讨论:我可以添加自定义属性html标记

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?

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

然后,使用$(本).attr(数据索引URL)jQuery中访问呈现剃刀标记。

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

3)将C#隐入输入字段在您的视图,并阅读您的JS文件隐藏的输入。

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

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

要在jQuery的阅读,你可以使用$(#indexUrl)。VAL()

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

这篇关于在CSHTML剃刀意见分离的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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