Why am I getting 404 error while accessing controller method in Ajax?

I have a ValidationController controller and it has a method called EmailExist

I have ajax call

 $.ajax({ type: "POST", url: "/Validation/EmailExist", data: { 'Email': $('#Email').val() }, success: function (result) { if (result == true) { alert("true"); } else { alert("false"); } }, error: function (error) { alert(error.responseText); } 

I get 404 error and I don't know why? Any suggestions or suggestions for debugging this?

+4
source share
1 answer

You have a hardcoded url:

 url: "/Validation/EmailExist" 

This is very bad . You should always use URL helpers when working with URLs:

 url: "@Url.Action("EmailExist", "Validation")" 

The reason this is bad is because, since you hard-coded the URL, you no longer rely on your route configuration. If you change your routes in Global.asax, your code will break. Your code will also be broken when you deploy your application to IIS, because there is now a virtual directory name that you must consider. Therefore, the correct URL is no longer /Validation/EmailExist , but /MyAppName/Validation/EmailExist . All these things are taken into account by helpers and that is the reason you should always use them.

Of course, if it is in a separate javascript file in which you do not have access to the server code, you can use the HTML5 data attributes in your DOM to put the correct URL or directly use any existing element, for example form action or anchor href.

+3
source

Source: https://habr.com/ru/post/1412615/


All Articles