weixin_33721427 2014-10-12 13:13 采纳率: 0%
浏览 28

如何拨打AJAX电话

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. Am I correctly accessing the URL?

Update: The following is the error message: "NetworkError: 404 Not Found - protocol://localhost:port/Controller/@Url.Action(%22GetUpdate%22)"

The following works through Fiddle: protocol://localhost:port/Controller/GetUpdate

  • 写回答

2条回答 默认 最新

  • weixin_33696106 2014-10-12 15:22
    关注

    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.
    '@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.

    Here's what you can do:

    • In the .cshtml file you can store the generated URL in a JavaScript variable and pass it to the external JS file.
    • You can move your external JavaScript to the .cshtml file so you can use Razor.
    • use a relative string path like /Controller/GetUpdate

    I would recommend the first one.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog