[英]How to make AJAX calls
I am aware this question has been answered before but I am somehow unable to hit an action within my controller. 我知道之前已经回答了这个问题,但是我无法以某种方式在控制器中执行操作。
Here is the Action 这是动作
public JsonResult GetUpdate()
{
//get a list of valid elements
var result = getContent();
return Json(result, JsonRequestBehavior.AllowGet);
}
In my script: 在我的脚本中:
$.ajax({
type: 'GET',
url: '@Url.Action("GetUpdate")',
dataType: 'json',
success: function (constraints) {
alert("Application updated");
},
error: function (ex) {
alert('Failed to retrieve update.' + ex);
}
});
Using fiddler I can hit GetUpdate but from the browser the Ajax call fails. 使用提琴手,我可以命中GetUpdate,但是从浏览器中,Ajax调用失败。 Am I correctly accessing the URL?
我可以正确访问URL吗?
Update: The following is the error message: "NetworkError: 404 Not Found - protocol://localhost:port/Controller/@Url.Action(%22GetUpdate%22)" 更新:以下是错误消息:“网络错误:404未找到-protocol:// localhost:port/Controller/@Url.Action(%22GetUpdate%22)”
The following works through Fiddle: protocol://localhost:port/Controller/GetUpdate 以下通过Fiddle工作:protocol:// localhost:port / Controller / GetUpdate
Razor code (C# and all other server-side script) is only executed from .cshtml
files, therefore C# and Razor can't be used in .js
files. Razor代码(C#和所有其他服务器端脚本)仅从
.cshtml
文件执行,因此C#和Razor不能在.js
文件中使用。
'@Url.Action("GetUpdate")'
doesn't generate a URL, it's just a string, therefore you are trying to request protocol://domain:port/Controller@Url.Action("GetUpdate")
which doesn't exist . '@Url.Action("GetUpdate")'
不会生成URL,它只是一个字符串,因此您正在尝试请求protocol://domain:port/Controller@Url.Action("GetUpdate")
,但不会不存在 。
Here's what you can do: 您可以执行以下操作:
.cshtml
file you can store the generated URL in a JavaScript variable and pass it to the external JS file. .cshtml
文件中,您可以将生成的URL存储在JavaScript变量中,并将其传递给外部JS文件。 .cshtml
file so you can use Razor. .cshtml
文件,以便可以使用Razor。 /Controller/GetUpdate
/Controller/GetUpdate
I would recommend the first one. 我会推荐第一个。
You can try this out,where _ApplicationPath is protocol://localhost:port/ 您可以尝试一下,_ApplicationPath是protocol:// localhost:port /
$.ajax({ type: 'GET', url: _ApplicationPath + "/ControllerName/GetUpdate", dataType: 'json', success: function (constraints) { alert("Application updated"); }, error: function (ex) { alert('Failed to retrieve update.' + ex); } });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.