Ajax调用进入MVC控制器 - 网址问题 [英] Ajax call Into MVC Controller- Url Issue

查看:109
本文介绍了Ajax调用进入MVC控制器 - 网址问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看了看previously-发布的jQuery / MVC的问题,并没有找到一个可行的答案。

I've looked at the previously-posted jQuery/MVC questions and haven't found a workable answer.

我有以下的JavaScript code:

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());
 }
});

在调用该地址后的样子:

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> 

可能有人请向我解释为什么它返回它像这样(的逻辑背后),并提供我一个有效的解决方案。在此先感谢!
PS:其他信息:%22是URL编码参考&LT;&LT;>>字符

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必须被放置在剃刀视图中,使该行

In order for this to work that Javascript must be placed within a Razor view so that the line

@Url.Action("Action","Controller")

被剃刀分析和实际值代替。

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文件

$.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());
});

或可选择地看着撬动框架的内置的<一个href="http://stackoverflow.com/questions/1305601/how-to-post-asp-net-mvc-ajax-form-using-javascript-rather-than-submit-button">Ajax没有污染与JS code你的看法。

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控制器 - 网址问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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