I’ve been developing an MVC 4 application that also includes Ajax via Jquery.
And I got a problem.
For example if I click a button, the onclick event fires a javascript method. This method is in a .js File.
That javascript method uses Ajax to call an ActionResult which receives some parameters (string, int) nothing special. So.. lets say my Action Result is in the “Person” Controller and that its name is “Add“. So I want to add a Person.
My url property in my ajax call should be "/Person/Add" and my data should be something like:
var person = new Object();
person.name = "John";
person.id = 1;
data: person
This works without any problem when running the application with Visual Studio. But when I deploy it in IIS I get a 404 Error.
I’ve try this. I added a <link> <link id="PersonAddURL" href="Url.Content("~/Person/Add") /> in the layout and then instead of using url: "/Person/Add" I changed it to url: $("#PersonAddURL").attr("href").
This works, now, I dont think is a good way to solve it. There should be another one better. And still even if I managed to solve it, I would like someone to explain me the reason this is happening. I dont like the idea of having one link tag for each Url.
Thanks for the future answers.
What I usually do is have the following global javascript variable in my ASP.NET MVC layout:
then from any JS file you can do the following:
just make sure you declare and initialize the webroot variable before any AJAX calls.
If you are using namespaces in your javascript then you could change it to (assuming app namespace):
and remove the global variable that makes developers uncomfortable.