$ajax 内的相对 URL 与 asp.net mvc 3

发布于 2024-12-22 03:33:33 字数 268 浏览 5 评论 0原文

我知道可以使用此函数

@Url.Action("MyInfo", "Home")

来避免对 url 进行硬编码,但我的 $.ajax 调用位于单独的 .js 文件中。上面的方法还有效吗?

据我所知,@Url.Action 只能在 Razor 文件内工作。但考虑到我们建议使用非侵入式 JS,我不太确定如何使用 @Url.Action

请指教。

I know one can use this function

@Url.Action("MyInfo", "Home")

to avoid the hardcoding of urls, but my $.ajax calls are in a separate .js file. Would the above still work?

From my knowledge, the @Url.Action will only work inside the Razor file. But considering that we are advised to use non-obtrusive JS, I am not quite sure how I would use the @Url.Action.

Please advise.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

土豪我们做朋友吧 2024-12-29 03:33:33

上面的方法还有效吗?

不。

据我所知,@Url.Action 只能在 Razor 文件内工作

您的知识是正确的。

但是考虑到我们被建议使用非侵入性的JS,我不这么认为
非常确定我将如何使用@Url.Action。

您可以在您正在不显眼地增强的某些 DOM 元素上使用 HTML5 data-* 属性(除非该元素已经是

或锚点,在这种情况下它已经包含 url):

<div id="foo" data-url="@Url.Action("foo")">Hello</div>

然后在您单独的 javascript 文件中:

$(function() {
    $('#foo').click(function() {
        var url = $(this).data('url');
        // TODO: do something with the url
    });
});

Would the above still work?

No.

From my knowledge, the @Url.Action will only work inside the Razor file

Your knowledge is correct.

But considering that we are advised to use non-obtrusive JS, I am not
quite sure how I would use the @Url.Action.

You could use HTML5 data-* attributes on some DOM element that you are unobtrusively enhancing (unless this element is already a <form> or an anchor in which case it already contains an url):

<div id="foo" data-url="@Url.Action("foo")">Hello</div>

and then in your separate javascript file:

$(function() {
    $('#foo').click(function() {
        var url = $(this).data('url');
        // TODO: do something with the url
    });
});
最偏执的依靠 2024-12-29 03:33:33

为相对路径添加函数参数。例如,在您的 View:

<script type="text/javascript">
   var path =  "@Url.Action("ActionName", "ControllerName")";

   someAjaxMethod(path)
</script>

和外部 js 文件中:

function someAjaxMethod(path)
{
   var data = {};
   $.ajax(path, data)
}

Add a function parameter for the relative paths. E.g., in your View:

<script type="text/javascript">
   var path =  "@Url.Action("ActionName", "ControllerName")";

   someAjaxMethod(path)
</script>

and in your external js file:

function someAjaxMethod(path)
{
   var data = {};
   $.ajax(path, data)
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文