简体   繁体   中英

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

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.

You can try this out,where _ApplicationPath is 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);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM