asp.net-MVC:剃刀“@”在js文件标志 [英] asp.net-mvc: razor '@' symbol in js file
问题描述
我有一个 .csHtml
-razor与使用 @ Url.Content
C#功能的JavaScript函数文件里面的AJAX网址。结果
我想该功能转移到从我的观点所引用的的.js
文件。
I have a .csHtml
-razor file with a javascript function that uses the @Url.Content
C# function inside for the ajax URL.
I want to move that function to a .js
file referenced from my view.
问题在于JavaScript不知道 @
符号,并不能解析的C#code。结果
有没有从视图中引用的.js
文件的方式@符号?
The problem is that javascript doesn't "know" the @
symbol and doesn't parse the the C# code.
Is there a way to reference .js
files from view with "@" symbol?
推荐答案
您可以使用HTML5 数据 - *
属性。让我们假设你想被点击,如一个div一些DOM元素时执行某些操作。所以:
You could use HTML5 data-*
attributes. Let's suppose that you want to perform some action when some DOM element such as a div is clicked. So:
<div id="foo" data-url="@Url.Content("~/foobar")">Click me</div>
,然后在单独的JavaScript文件中,你可以与DOM悄悄地工作:
and then in your separate javascript file you could work unobtrusively with the DOM:
$('#foo').click(function() {
var url = $(this).data('url');
// do something with this url
});
这种方式,你可以有标记和脚本之间的分离纯没有你永远不需要任何服务器端代码中的JavaScript文件。
This way you could have a pure separation between markup and script without you ever needing any server side tags in your javascript files.
这篇关于asp.net-MVC:剃刀“@”在js文件标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!