Ajax 调用到 MVC 控制器 - URL 问题 [英] Ajax call Into MVC Controller- URL Issue
问题描述
我查看了之前发布的 jQuery/MVC 问题,但没有找到可行的答案.
I've looked at the previously-posted jQuery/MVC questions and haven't found a workable answer.
我有以下 JavaScript 代码:
I have the following JavaScript code:
$.ajax({
type: "POST",
url: '@Url.Action("Search","Controller")',
data: "{queryString:'" + searchVal + "'}",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
alert("here" + data.d.toString());
}
});
当调用 Url 时,帖子看起来像:
When calling the Url the post looks like:
NetworkError: 500 Internal Server Error - <a href="http://localhost/Web/Navigation/@Url.Action(%22Search%22,%22Chat%22)"></a>
有人可以向我解释为什么它会像这样返回它(背后的逻辑)并为我提供一个有效的解决方案.提前致谢!
P.S.:附加信息:%22 是 <<>> 的 URL 编码参考.字符
Could someone please explain to me why does it return it like this ( the logic behind it ) and offer me a valid solution. Thanks in advance!
P.S.: Additional Information: %22 is the URL Encoding Reference for <<">> character
推荐答案
为了让这个工作,JavaScript 必须放在 Razor 视图中,这样行
In order for this to work that JavaScript must be placed within a Razor view so that the line
@Url.Action("Action","Controller")
由 Razor 解析并替换实际值.
is parsed by Razor and the real value replaced.
如果您不想将 JavaScript 移动到您的视图中,您可以考虑在视图中创建一个设置对象,然后从您的 JavaScript 文件中引用该对象.
If you don't want to move your JavaScript into your View you could look at creating a settings object in the view and then referencing that from your JavaScript file.
例如
var MyAppUrlSettings = {
MyUsefulUrl : '@Url.Action("Action","Controller")'
}
并在您的 .js 文件中:
and in your .js file:
$.ajax({
type: "POST",
url: MyAppUrlSettings.MyUsefulUrl,
data: "{queryString:'" + searchVal + "'}",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
alert("here" + data.d.toString());
}
});
或者考虑利用框架的构建 在 Ajax
or alternatively look at levering the framework's built in Ajax methods within the HtmlHelpers which allow you to achieve the same without "polluting" your Views with JS code.
这篇关于Ajax 调用到 MVC 控制器 - URL 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!