0

My ajax call to the controller works for some pages like http://localhost:2493/anything, and does not work for http://localhost:2493/Account/Login.

this code work for the index page

$(document).ready(function () {
    $.ajax({
          url: 'Home/GetLinks',
          contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        $.each(data, function (index, val) {
        $('#ListLinks').append('<li><a href="http://'+ val.Url +'" target="_new">' + val.Url + '</a></li>');
    });
    },
    error: function (xhr, status, err) {
        console.log('Response code:' + xhr.status);
        console.log('[Error:' + err + '] ' + status);
    }
     });
});

When debug this code on pages like http://localhost:2493/Account/Login I got a error 404.

The JS code is placed in separeted file and its called on the _layout page.

I know the problem is url, so I tried to change the code and use

url: '@Url.Action("Home","GetLinks")',

Then it doesn't work on any page.

How can I write this bit code to work on any page.

Thanks a lot

2 Answers 2

1

Try adding a leading slash to the URL parameter of the ajax call.

This means get the URL from the root of the domain:

$.ajax({
          url: '/Home/GetLinks',
Sign up to request clarification or add additional context in comments.

Comments

0

Your html helper Url.Action method won't work in your external js file. So create js variable( in global scope) in your razor view/Layout file and use that in your external javascript file.

In your razor file

<script type="text/javascript">
  var global_GetLinks_Url="@Url.Action("GetLinks","Home")";
</script>

now you can access the global_GetLinks_Url in your external js files

$(document).ready(function () {
    $.ajax({
          url: global_GetLinks_Url,
          //rest of your code goes here
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.