asp.net-mvc:js 文件中的剃刀“@"符号 [英] asp.net-mvc: razor '@' symbol in js file
问题描述
我有一个带有 javascript 函数的 .csHtml
-razor 文件,该函数在内部使用 @Url.Content
C# 函数作为 ajax URL.
我想将该函数移动到从我的视图中引用的 .js
文件中.
问题在于 javascript 不知道"@
符号并且不解析 C# 代码.
有没有办法从带有@"符号的视图中引用 .js
文件?
您可以使用 HTML5 data-*
属性.假设您想在单击某个 DOM 元素(例如 div)时执行某些操作.所以:
点击我
然后在您单独的 javascript 文件中,您可以不显眼地使用 DOM:
$('#foo').click(function() {var url = $(this).data('url');//用这个 url 做一些事情});
通过这种方式,您可以在标记和脚本之间实现纯粹的分离,而无需在 javascript 文件中添加任何服务器端标签.
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.
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?
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>
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
});
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屋!