开发者

How can I use Razor expressions within a Coffeescript file?

I would like to do something like this in CoffeeScript so that I can move all my script off into coffe files:

$("#btnFinish").click ->
    $.post "@Url.Action("Submit", "Process")", 开发者_Python百科(response) ->
        $("#PlaceHolderButton")
            .button()
            .text response

$("#btnHome").click -> 
    window.location.href='@Url.Action("Index","Home")'

Should I just push the url and other items I need into hidden values and query them for the later when the script runs?

I feel like I am missing a key concept or something here.


Try to avoid the need of mixing javascript with server side. There are always better workarounds. For example:

@Html.ActionLink("Some button", "Submit", "Process", null, new { id = "btnFinish" })

and then in your js:

$('#btnFinish').click(function() {
    $.post(this.href, function(response) {
        ...
    });
    return false;
});

or if btnFinish is some div for which you cannot use a helper to generate an url, you could use HTML5 data-* attributes, like so:

<div id="btnFinish" data-url="@Url.Action("Submit", "Process")">Some button</div>

and then:

$('#btnFinish').click(function() {
    var url = $(this).data(url);       
    $.post(url, function(response) {
        ...
    });
    return false;
});

but if you have some clickable button which you AJAXify the first approach would be semantically better because you are directly having the url as part of the href.

The same thing applies for your second example:

$('#btnHome').click(function() {
    window.location.href = $(this).data('url');
});

So you no longer need any server side tags in your javascript files. Your js are completely static, combined, minified, gzipped, cached, served from a content delivery network and all the benefits related to this.


Well to embed Razor directly into JavaScript you would need the JavaScript to go through the Razor view engine to be evaluated before it is handed off to the browser. That doesn't happen currently but it could be done.

I've worked around this with these methods: - hidden field approach - <script type="text/javascript>...</script> in the view

You could use that last method and make a configuration management plug-in that would take in key-values in the view and provide a method to query for them from the JavaScript outside of the view.

There is also RazorJS which is available on Nuget:

http://nuget.org/List/Packages/RazorJS

Write Razor-Style C# or VB.NET insde your Javascript Files. Also contains an http handler for serving, when needed, those files.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜