Asp.Net的mvc Url.Action外部JS文件? [英] Asp.Net Mvc Url.Action in external js file?

查看:873
本文介绍了Asp.Net的mvc Url.Action外部JS文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在外部js文件,我不能使用

In external js file, I cant use

url = "@Url.Action("Action", "Controller")" 
//url output : @Url.Action("Action", "Controller")
//I get IllegalPath Name error.

当我写的是这样的:

url = "/Controller/Action"

和项目如果是子文件夹下,然后脚本不工作。我需要像这样的相对URL:

And If project is under a sub folder, then scripts do not work. I need something like this as relative Url:

url = "~/Controller/Action"

我怎么能这样做呢?谢谢你。

How can ı do this? Thanks.

推荐答案

由于.js文件不被asp.net mvc的视图引擎解析,你根本无法使用任何C#code在那里。我会建议使用不显眼的方式,像这样

As .js files are not parsed by asp.net mvc view engine, you simply cannot use any c# code in there. I would suggest using unobtrusive approach, something like this

<div id="loader" data-request-url="@Url.Action("Action", "Controller")"></div>

和在JavaScript中,数据请求URL的使用价值

And in javascript, use value of data-request-url

$(function(){
   $('#loader').click(function(){
       var url = $(this).data('request-url');
       alert(url);
   });
});

这篇关于Asp.Net的mvc Url.Action外部JS文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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