asp.net-mvc: razor '@' symbol in js file

2019-01-04 09:34发布

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?

9条回答
成全新的幸福
2楼-- · 2019-01-04 10:11

Well I've just found a razor engine on nuget that does it! Meaning solves @ syntax!
It's name is RazorJS.

The Nuget package


2016 Update:
The package wasn't updated for 5 years, and the project site link is dead. I do not recommend people to use this library anymore.

查看更多
SAY GOODBYE
3楼-- · 2019-01-04 10:14

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.

查看更多
狗以群分
4楼-- · 2019-01-04 10:16

I usually wrap JS needing access to model properties, in functions and then pass the @something in the view. For example

<script type="text/javascript">
function MyFunction(somethingPresentInTheView) {
  alert(somethingPresentInTheView);
}
</script>

in the view I add function invocation via (just an example):

<input type='button' onclick="MyFunction('@Model.PropertyNeeded')" />
查看更多
登录 后发表回答