我如何得到正确的URL使用jQuery / AJAX当一个MVC动作?正确、动作、URL、jQuery

2023-09-10 21:40:03 作者:那年夏天丶浅浅の笑

所以,我有我的第一个MVC2网站,我的工作,自然我想抛出一些AJAX在那里。现在的问题是,是,我不知道如何在一个URL参数传递时,你得到的URL行动。让我解释。我见过到目前为止的例子显示了开发商的传球像'/ myController的/ MyAction的字符串。这是伟大的,但如果你的控制器是不是在你的网站的根目录下(如在我的情况的情况下)。我总是可以使用像MyAction的相对URL,除非该URL包含也不行参数。考虑 http://example.com/myroot/MyController/MyAction VS的 http://example.com/myroot/MyController/MyAction/PageNumber/SomeOtherValue 。现在的相对URL将是不正确的。

So I have my first MVC2 site that I'm working on and naturally I'd like to throw some AJAX in there. The problem is, is that I don't know how to get the URL for the action when passing in a URL parameter. Let me explain. The examples I've seen so far show the developer passing in strings like '/MyController/MyAction'. That's great, except if your controllers are not in the root directory of your website (as is the case in my situation). I could always use relative URLs like 'MyAction' except if the URL contains parameters that doesn't work either. Consider http://example.com/myroot/MyController/MyAction vs http://example.com/myroot/MyController/MyAction/PageNumber/SomeOtherValue. Now the relative URL will be incorrect.

在ASPX code,这很容易。我只写与<%= Url.Action(MyAction的)%>。但我怎么做怎么在我的JavaScript文件?

In the ASPX code, this is easy. I just write in <%= Url.Action("MyAction") %>. But how do I do this in my javascript file?

推荐答案

这是一部分长期存在的问题是,包括服务器,双面code在JavaScript文件是不是真的有可能:(。(如果没有严重的黑客攻击,那是。)

This is part of the long-standing issue that including server-sided code in JavaScript files is not really possible :(. (Without serious hacks, that is.)

最好的解决办法是包括你的HTML文件中的操作URL的某处,然后得到的JavaScript值。我的建议是这样的:

The best solution is to include the action URL inside your HTML file somewhere, then get that value from JavaScript. My suggestion would be something like this:

<!-- in your view file  -->
<form id="MyForm" action="<%: Url.Action("MyAction") %>"> ... </form>

<!-- or -->
<a id="MyLink" href="<%: Url.Action("MyAction") %>"> ... </a>

结合

// In your .js file
$("#MyForm").submit(function ()
{
    $.post($(this).attr("action"), data, function (result) { /* ... */ });
    return false;
});

// or
$("#MyLink").click(function ()
{
    $.getJSON($(this).attr("href"), data, function (result) { /* ... */ });
    return false;
});

这感觉语义清楚地知道,在某些情况下甚至造成时,JavaScript是关闭状态的可降解的备用行为。

This feels semantically clear to me, and in some cases even creates degradable fallback behavior for when JavaScript is turned off.